平展嵌套分组的 Linq 查询,ASP.net 中的组合键
本文关键字:ASP net 组合 Linq 嵌套 查询 | 更新日期: 2023-09-27 18:17:59
在我的数据库中,有一些玩家对象确实有国籍和积分。
我需要一种嵌套我的分组的可能性。因为它们是由客户端提供的,所以分组到一个匿名密钥中似乎没有选择。所以我必须像嵌套它们一样
Players.Where(p => p.Created <= /*some date*/)
.GroupBy(p => p.Nationality) // group them by their nationality
.Select(arg => new {
arg.Key,
Elements = arg.GroupBy(p => p.Points > 0) // group them by the ones with points and the ones without
})
. // here i need to flatten them by also combining the key(s) of the groupings to put them into a dictionary
.ToDictionary(/*...*/);
最后,Dictionary
应该包含键,如string
["USA|true"]
、["USA|false"]
或["GER|true"]
及其各自的元素。
我想SelectMany
是关键,但我不明白从哪里开始实现这一目标。
这个解决方案怎么样:
public class Player
{
public string Nationality {get;set;}
public int Points {get;set;}
public double otherProp {get;set;}
//new field is added
public string groupings {get;set;}
}
var groups = new List<Func<Player, string>>();
groups.Add(x => x.Nationality);
groups.Add(x => (x.Points > 0).ToString().ToLower());
Players.ForEach(x =>
groups.ForEach(y => x.groupings = x.groupings + (x.groupings == null ? "" : "|") + y(x))
);
var answer = Players.GroupBy(x => x.groupings).ToDictionary(x => x.Key, x => x.ToList());
回答您的具体问题。
正如你提到的,SelectMany
是关键。查询中的位置紧跟在Select
之后:
.Select(...)
.SelectMany(g1 => g1.Elements.Select(g2 => new {
Key = g1.Key + "|" + g2.Key, Elements = g2.ToList() }))
.ToDictionary(g => g.Key, g => g.Elements);
它也可以替换Select
(即在第一个GroupBy
之后立即开始(:
.GroupBy(p => p.Nationality)
.SelectMany(g1 => g1.GroupBy(p => p.Points > 0).Select(g2 => new {
Key = g1.Key + "|" + g2.Key, Elements = g2.ToList() }))
.ToDictionary(g => g.Key, g => g.Elements);