【问题标题】:Groupby and Sum from a datatable or dataview数据表或数据视图中的 Groupby 和 Sum
【发布时间】:2018-04-03 09:25:52
【问题描述】:

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

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

现在,我尝试创建一个 groupby(带有“名称”列)并从另一列“数量”中求和。

其实:

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

我会像这样返回一个数据表或数据视图:

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

我该怎么做?

对不起,如果这很简单,但我不喜欢那个。

【问题讨论】:

    标签: vb.net datatable grouping dataview


    【解决方案1】:

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

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

    现在您可以创建结果表了:

    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

    【讨论】:

    • 非常感谢您的快速回复和解释。这很清楚,我成功地使用了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2019-04-09
    • 2021-01-17
    • 2020-08-18
    • 2016-09-11
    • 1970-01-01
    相关资源
    最近更新 更多