0

这是我的数据表

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 的情况下做到这一点,那就太棒了。

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

4

1 回答 1

0

When you use Group by in Linq you can get to the underlying items as an Enumberable. All you need to do is another Select to get just the values you want

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})
                                 };
于 2013-08-30T17:17:09.563 回答