TIL

Today I Learned. 知ったこと、学んだことを書いていく

LINQでGroupBy - VB.NET

LINQについて知るには

を知っておかないといけない

こちらのサイトのソースをそのまま、コピペしたみたいな感じになっている...

理解して書かないとダメです...

''' <summary>
''' 理解してないから、まとめないと!!!
''' 参考サイト
''' https://qiita.com/nskydiving/items/c9c47c1e48ea365f8995
''' </summary>
Module Module1

    Sub Main()
        Dim testList As New List(Of TestClass)

        testList.Add(New TestClass With {.Name = "foo", .Color = "red", .Num = 1})
        testList.Add(New TestClass With {.Name = "bar", .Color = "red", .Num = 7})
        testList.Add(New TestClass With {.Name = "foo", .Color = "yellow", .Num = 4})
        testList.Add(New TestClass With {.Name = "foo", .Color = "red", .Num = 9})

        ' Name と Color でグルーピングして、
        ' Numの合計値を求める
        Dim group = testList.GroupBy(Function(g) Tuple.Create(g.Name, g.Color)).
            Select(Function(x) New With {.name = x.Key.Item1, .color = x.Key.Item2, .sumNum = x.Sum(Function(s) s.Num)}).
            ToList()

        For Each item In group
            Debug.WriteLine(item.name & ", " & item.color & ", " & item.sumNum)
        Next

        ' 出来た!!!
        ' foo, red, 10
        ' bar, red, 7
        ' foo, yellow, 4
    End Sub

End Module

Public Class TestClass

    Property Name As String
    Property Color As String
    Property Num As Integer

End Class

参考文献