数据表或数据视图中的 Groupby 和 Sum

Groupby and Sum from a datatable or dataview

我有一个包含不同种类水果和豆类的数据表(由 xls 文件填充)。

我从这个数据表创建了一个数据视图,并使用 RowFilter 只包含土豆和西红柿。

现在,我尝试创建一个分组(使用 'Name' 列)并从另一列 'Quantity' 中求和。

实际上:

Name    |  Quantity  | color
tomatoe |     2      |  red
tomatoe |     1      |  red
potatoe |     5      |  yellow
tomatoe |     1      |  red
potatoe |     1      |  yellow

我会 return 像这样的数据表或数据视图 :

Name    |  Quantity | color
tomatoe |     4     |  red
potatoe |     6     |  yellow

我该怎么做?

对不起,如果这很简单,但我对此一窍不通。

使用LINQ,本例为Linq-To-DataTable

Dim fruitGroups = table.AsEnumerable().GroupBy(Function(row) row.Field(Of String)("Name"))

现在您可以创建结果 table:

Dim tableResult = table.Clone() ' empty table with same columns
For Each grp In fruitGroups 
    tableResult.Rows.Add(grp.Key, grp.Sum(Function(row) row.Field(Of Int32)("Quantity")), grp.First().Field(Of String)("Color"))
Next

这将为每个组(第一个)取一个任意颜色。因此,如果您想按 NameColor 的组合进行分组,则必须按包含以下两者的匿名类型进行分组:

Dim fruitGroups = table.AsEnumerable().
    GroupBy(Function(row) New With {
        Key .Name = row.Field(Of String)("Name"),
        Key .Color = row.Field(Of String)("Color")
    })

Dim tableResult = table.Clone()
For Each grp In fruitGroups
    tableResult.Rows.Add(grp.Key.Name, grp.Sum(Function(row) row.Field(Of Int32)("Quantity")), grp.Key.Color)
Next

如果您需要 DataView,您可以使用 tableResult.DefaultView