使用LINQ将DataSet列值分组为逗号分隔字符串

时间:2014-06-02 17:51:46

标签: vb.net linq

如何在LIN.NET中将使用LINQ的数据集中的列值组合成一个逗号分隔值的单个字符串?

我有一个具有以下结构的表

ID        Name
728       Jim
728       Katie
728       Rich 

如何将这些组合成一行,如下所示

ID   Name
728  Jim,Katie,Rich

请注意我使用的是LINQ to Dataset,因此请以适用的语法回复。

4 个答案:

答案 0 :(得分:1)

这是一个例子(使用LINQ to objects,但是应该很容易调整LINQ to DataSet):

Class Record
  Public Property ID As Integer
  Public Property Name As String
  Sub New(id As Integer, name As String)
    Me.ID = id
    Me.Name = name
  End Sub
End Class

Sub Main()
  Dim recordList As New List(Of Record)

  recordList.Add(New Record(728, "Jim"))
  recordList.Add(New Record(728, "Katie"))
  recordList.Add(New Record(728, "Rich"))

  recordList.Add(New Record(729, "John"))
  recordList.Add(New Record(729, "Michael"))

  Dim v = From r As Record In recordList
          Group By ID = r.ID Into Records = Group
          Select ID, Name = String.Join(","c, Records.Select(Function(x) x.Name))
End Sub

答案 1 :(得分:0)

这应该做你想要的:

Dim result = list.GroupBy(Function(a) a.ID) _
.Select(Function(g) New With {.ID = g.Key, .csvList = g.Select(Function(n) n.Name) _ 
.Aggregate(Function(accumulation, current) accumulation + "," + current)}) _
.ToList()

答案 2 :(得分:0)

这是使用LINQ to Dataset的示例:

Dim grouped =
    From row In dt.AsEnumerable()
    Group row By id = row.Field(Of Integer)("ID") Into Group
    Select ID, Name = String.Join(",", From i In Group Select i.Field(Of String)("Name"))

答案 3 :(得分:0)

很晚但我也遇到了同样的问题,这是我的解决方案。希望这有助于某人

 Dim grouped = 
        a.AsEnumerable().
          GroupBy(Function(row) row.Field(Of Integer)("ID")).
          Select(Function(group, ID)
                     Return New With
                     {
                         .ID= ID,
                         .Name= String.Join(",", group.Select(Function(row) row.Field(Of String)("Name")))
                     }
                 End Function)