0

我已经在网上搜索过,但无法通过使用 LINQ 或仅通过对象列表中的 group by 来掌握该组。我需要按列表内对象的属性进行分组,以便它组合每个位置的数量(删除重复数据)。

假设列表对象是这个 Property Site Property Quantity

该列表包含

Item(0).Site = 001
Item(0).Quantity = 100
Item(1).Site = 001
Item(1).Quantity = 200
Item(2).Site = 002
Item(2).Quantity = 100
Item(3).Site = 002
Item(3).Quantity = 200

我需要按站点分组,以便它在最终列表中结束

Item(0).Site = 001
Item(0).Quantity = 300
Item(1).Site = 002
Item(1).Quantity = 300

我使用确实包含上述​​ 2 个属性以及其他属性的 VB.Net 和 List(Of CustomDT)。

4

1 回答 1

1

如果您了解如何在 SQL 中进行分组,这并不难。对我来说,最好的理解就是举例。下面我只是动态地创建两个人并将他们放入一个集合中。我的结果是获得按年龄分组的人员列表。因此,您拥有 KeySelector,它是您用作 GroupBy 操作的键,ElementSelector 是您想要总结的元素的 IEnumerable(Of T),最后记录选择器用于组合 Key 和IEnumerable 变为一个新值。要记住的一个想法是,当您使用 ValueObjects 或 Dynamic Objects 时,您需要确保覆盖 GetHash 和 Equals To。我已经写了一篇关于为 ExpandoObject 创建一个比较器的博客,其中包含指向 GitHub 的链接以获取示例代码,以防你想让它工作。如果是这种情况,您将不得不在 RecordSelector 之后添加一个比较器。我希望这有帮助。

http://wysnet.blogspot.com/2013/08/comparer-for-expandoobject.html?view=magazine

    Dim person1 As Object = New Dynamic.ExpandoObject
    person1.Name = "John"
    person1.Age = 10


    Dim person2 As Object = New Dynamic.ExpandoObject
    person2.Name = "Jake"
    person2.Age = 10

    Dim people As New List(Of Object)
    people.AddRange({person1, person2})

    Dim personByAge = people.GroupBy(keySelector:=Function(i) i.Age,
                                     elementSelector:=Function(e) e.Name,
                                     resultSelector:=Function(k, e)
                                                         Dim groupbyItem As Object = New Dynamic.ExpandoObject
                                                         groupbyItem.Key = k
                                                         groupbyItem.People = New List(Of String)(e)
                                                         Return groupbyItem
                                                     End Function)
于 2013-09-09T00:55:08.953 回答