如何使用LINQ
来实现以下目标?
我有一些c#对象(我将它们写为JSON
仅用于简化)
{ Name: A, Domain: a, SubDomain: 1}
{ Name: B, Domain: a, SubDomain: 2}
{ Name: C, Domain: b, SubDomain: 1}
{ Name: D, Domain: b, SubDomain: 2}
{ Name: E, Domain: c, SubDomain: 1}
我想把它们收集起来:
{ Domain: a ,{{Name: A, SubDomain: 1}, {Name: B, SubDomain: 2}}
Domain: b ,{{Name: C, SubDomain: 1}, {Name: D, SubDomain: 2}}
Domain: c ,{{Name: E, SubDomain: 1}}
答案 0 :(得分:8)
您只想按Domain
分组?
var list = GetListFromFoo();
var groupedList = list.GroupBy(x => x.Domain);
使用此LINQ
方法完成:
public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
如果我理解你的评论,那就是你要找的:
var groupedList = list.GroupBy(x => x.Domain, x => new
{
x.Name,
x.SubDomain
});