3

我该如何使用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}}
4

1 回答 1

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)

MSDN


如果我理解你的评论是正确的,这就是你要找的:

var groupedList = list.GroupBy(x => x.Domain, x => new
                                        {
                                            x.Name,
                                            x.SubDomain
                                        });

MSDN

于 2012-04-04T12:04:36.480 回答