【问题标题】:Vb.net pare down a lists of objects [closed]Vb.net减少对象列表[关闭]
【发布时间】:2015-07-20 01:53:52
【问题描述】:

我有一个我需要削减的对象列表。这些项目是可变的,所以我不能真正暴力破解它。

这就是我想要做的......

对象的原始列表...

“名称”:“苹果”,“数量”:1 “名称”:“香蕉”,“数量”:2 “名称”:“苹果”,“数量”:3 “名称”:“香蕉”,“数量”:4 “名称”:“草莓”,“数量”:5

削减后的对象列表...

“名称”:“苹果”,“数量”:4 “名称”:“香蕉”,“数量”:6 “名称”:“草莓”,“数量”:5

我在 .net 4.5 环境中工作,所以我愿意接受任何方法。

【问题讨论】:

  • 你想看看LINQ的GroupBy方法。如果您在使用它时遇到问题,请发布一个新问题。
  • 它是“pare down”,而不是“pair down”。

标签: .net vb.net linq


【解决方案1】:

所以你有一个包含名称和数量属性的对象列表?您可以使用分组依据和聚合:

var items = list _
     .GroupBy(Function(i) i.Name)  _
     .Select(Function(i) new Item With { .Name = i.Key, .Qty = i.Sum(Function(q) q.Qty) })

按名称分组,然后您可以使用 Sum 对项目总数求和。您也可以从another example 看到这一点。

【讨论】:

  • 这是一个 VB .NET 问题;你的答案是错误的语言。此外,查询语法在 VB .NET 中是惯用的。
  • 由于我使用的是 LINQ 方法方法,因此已编辑以放回句点和 _ 新行所需...
  • 如果行尾有句点,则vb中不再需要行继续符。
  • 好吧,我相信你的话......我没有意识到......
  • 行尾的分号不会使 VB 编译器快乐
【解决方案2】:

您可以考虑创建一个字典,将名称存储为键,然后将数字存储为值:

Private _dict As Dictionary(Of String, Integer)
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    _dict = New Dictionary(Of String, Integer)

    AddToDictionary("Apple", 1)
    AddToDictionary("Banana", 2)
    AddToDictionary("Apple", 3)
    AddToDictionary("Banana", 4)
    AddToDictionary("Strawberry", 5)


    'The following outputs:
    'Apple : 4
    'Banana : 6
    'Strawberry : 5

    For Each kvp In _dict
        Debug.WriteLine(kvp.Key & " : " & kvp.Value)
    Next
End Sub

Private Sub AddToDictionary(name As String, value As Integer)
    If _dict.ContainsKey(name) Then
        _dict(name) += value
    Else
        _dict.Add(name, value)
    End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2021-12-30
    • 2020-10-19
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多