简体   繁体   English

使用Linq按一列分组并按另一列区分

[英]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. 我正在使用Linq查询来对列名称进行分组并返回行列表。

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. 现在,在上面的示例中,Values是一个DataRow,而我刚刚给出了其中一个值的示例。 Now what I want is that for GroupDescription '1' the output only has one row with '12' value. 现在,我想要的是对于GroupDescription'1',输出仅具有'12'值的一行。 I have tried a few things one of which is to have another Linq query on first list but that's over complicating things. 我尝试了几件事,其中之一是在第一个列表上有另一个Linq查询,但这使事情复杂化了。 How do I use linq to group by first column and then use Distinct on certain column returned list to get only Distinct rows? 如何使用linq按第一列分组,然后对某些返回列的列表使用Distinct来仅获得Distinct行?

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()     
            };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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