【问题标题】:linq concat column by vallinq concat column by val
【发布时间】:2012-06-27 14:30:19
【问题描述】:

我只是在寻找如何使用 LINQ 对列表进行分组。

Class Item
    Public col1 As String
    Public col2 As String
    Public col3 As String
    Public description As String
    Public Sub New(ByVal col1 As String, ByVal col2 As String, 
                   ByVal col3 As String, ByVal description As String)
        Me.col1 = col1
        Me.col2 = col2
        Me.col3 = col3
        Me.description = description
    End Sub
End Class  


    Dim ItemList As New List(Of Item)
    ItemList.Add(New Item("A", "A", "A", "1"))
    ItemList.Add(New Item("A", "A", "A", "2"))
    ItemList.Add(New Item("A", "B", "A", "3"))
    ItemList.Add(New Item("A", "B", "A", "4"))
    ItemList.Add(New Item("A", "B", "B", "5"))
    ItemList.Add(New Item("A", "B", "C", "6"))

结果应该是 4 项的列表:

    '[0] = "A", "A", "A", "1 2"
    '[1] = "A", "B", "A", "3 4"
    '[2] = "A", "B", "B", "5"
    '[3] = "A", "B", "C", "6"

【问题讨论】:

    标签: vb.net linq list group-by


    【解决方案1】:

    如果我理解您按 3 列分组并加入它们的描述的要求,那么以下 LINQ 语句应该可以工作:

    var query = from item in ItemList
                group item by
                    new { Col1 = item.col1, Col2 = item.col2, Col3 = item.col3 }
                into g
                select new
                {
                     Col1 = g.Key.Col1,
                     Col2 = g.Key.Col2,
                     Col3 = g.Key.Col3,
                     Description = String.Join(" ", g.Select(xx => xx.description))
                };
    

    【讨论】:

    • 现在如何转换为 vb.net
    【解决方案2】:
    Class Item
        ...
        Public ReadOnly Property id As String
            Get
                Return col1 & "_" & col2 & "_" & col3
            End Get
        End Property
    End Class  
    
    Dim groups = ItemList.GroupBy(Function(item) item.id)
    Dim result = From g in groups
                 Select New Item(g(0).col1, g(0).col2, g(0).col3,
                                 String.Join(" "c, g.Select(Function(i) i.description)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-19
      • 2011-06-21
      • 1970-01-01
      • 2020-01-19
      相关资源
      最近更新 更多