简体   繁体   中英

Group by one column and Distinct by another column using Linq

I am using a Linq query to groupBy a column name and return a list of rows.

var query = from row in ProcessSummaryData.AsEnumerable()
            group row  by new { Key = row .Field<string>("GroupDescription") } into g
            select new 
           { 
             GroupDescription = g.Key, 
             Values = g.ToList(), 

           };

The output of this query is something like this

GroupDescription   Values
1                  12,abc,xyz
                   12,abx,yut
                   13,tye,lki

2                  14,asd,acd

Now the in the above example Values is a DataRow and I have just given an example of values in it. Now what I want is that for GroupDescription '1' the output only has one row with '12' value. I have tried a few things one of which is to have another Linq query on first list but that's over complicating things. How do I use linq to group by first column and then use Distinct on certain column returned list to get only Distinct rows?

To get the first occurrence of a field's values you can group by that field and then take the first row of each grouping.

var query = from row in ProcessSummaryData.AsEnumerable()
            group row  by new { Key = row .Field<string>("GroupDescription") } into g
            select new 
            { 
                GroupDescription = g.Key, 
                Values = (from value in g.ToList()
                          group value by value["Id"] into valueGroup
                          select valueGroup.First()).ToList()     
            };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM