[英]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.