Grouping with LINQ

How can I use LINQ

to achieve the following?

I have some C # object (I am writing these as JSON

just for simplicity)

{ 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}

      

I want to collect them like:

{ 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}}

      

+3


source to share


1 answer


Do you just want to group by Domain

?

var list = GetListFromFoo();
var groupedList = list.GroupBy(x => x.Domain);

      

It was done with this method LINQ

:

public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
    this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)

      

MSDN




If I understand your comment correctly, this is what you are looking for:

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

      

MSDN

+8


source







All Articles