繁体   English   中英

DataTable-Linq-根据分组选择不同的行

[英]DataTable - Linq - select distinct rows based on grouping

这是我的数据表

Type        Product  Action    Quantity
----------  -------  --------  --------
Fruit       Apple    Sales     1
Fruit       Apple    Sales     2
Fruit       Orange   Sales     3
Fruit       Orange   Picking   3
Vegetables  Carrot   Sales     1
Vegetables  Carrot   Sales     3
Vegetables  Carrot   Sales     3
Vegetables  Carrot   Pickings  3

目前我有这个

var tableColumnGrouping =
    from table in ReportConfigurationTable.AsEnumerable()
    group table by new
    {
        column1 = table["Type"],
        column2 = table["Product"]
    }
    into groupedTable
    select new
    {
        tableColumn = groupedTable.Key,  // Each Key contains column1 and column2
        tableColumnCount = groupedTable.Count() 
    };

这将为我提供以下变量:

{ column1 = "Fruit", column2 = "Apple" }
{ column1 = "Fruit", column2 = "Orange" }
{ column1 = "Vegetable", column2 = "Carrot" }

这是预期的。 现在,我想从DataTable中选择那些不同的值列分组与数据表相交的位置,然后获取Action | Quantity的唯一值。

因此,对于Fruit | Apple的分组,我将返回两行Sales | 1 Sales | 2。

或者,如果有一种非常聪明的方法而又不进行第二次foreach操作,那将是很棒的。

如何根据“类型” |“产品”上的分组从“操作” |“数量”列中获取唯一值?

在Linq中使用分组依据时,您可以将其作为一个Enumberable获得基础项目。 您需要做的就是另一个Select(选择)以仅获取所需的值

var rptTable = from t in ReportConfigurationTable.AsEnumerable()
                       select new {Type = t["Type"], Product = t["Product"], Action = t["Action"], Quantity = t["Quantity"]};


var tableColumnGrouping = from table in rptTable
                             group table by new { table.Type, table.Product }
                                 into groupedTable
                                 select new
                                 {
                                     tableColumn = groupedTable.Key,
                                     tableColumnCount = groupedTable.Count(),
                                     actions = groupedTable.Select(t => new {Action = t.Action, Quantity = t.Quantity})
                                 };

暂无
暂无

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

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