2014年4月14日月曜日

VB.NET LinqでGroupByの使い方

いつも使い方を忘れるのでメモ。 サンプルは、List型の配列、Dictionary型でGroupByする時の例。
    Public Class pmodel
        Public key As Integer = 0
        Public dat As String = ""

        Public Sub New(k As Integer, d As String)
            key = k
            dat = d
        End Sub
    End Class
    Private models As New List(Of pmodel)
    Private dic As New Dictionary(Of Integer, pmodel)


    Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
        models.Clear()
        models.Add(New pmodel(0, "A"))
        models.Add(New pmodel(0, "B"))
        models.Add(New pmodel(1, "C"))
        models.Add(New pmodel(2, "D"))
        models.Add(New pmodel(5, "E"))
        Dim dat1() As IGrouping(Of Integer, pmodel) = models.GroupBy(Function(zz As pmodel) zz.key).ToArray()
        For Each dat As IGrouping(Of Integer, pmodel) In dat1
            For Each d In dat
                Console.WriteLine(String.Format("key={0}, k={1}, v={2}", dat.Key, d.key, d.dat))
            Next
        Next
''' >>>key=0, k=0, v=A
''' >>>key=0, k=0, v=B
''' >>>key=1, k=1, v=C
''' >>>key=2, k=2, v=D
''' >>>key=5, k=5, v=E
''' 

        dic.Clear()
        dic(0) = New pmodel(0, "AA")
        dic(1) = New pmodel(1, "AA")
        dic(2) = New pmodel(2, "BB")
        dic(3) = New pmodel(3, "CC")
        dic(5) = New pmodel(5, "DD")

        Dim dat2() As IGrouping(Of String, pmodel) = dic.Values.GroupBy(Function(d As pmodel) d.dat).ToArray()
        For Each dat As IGrouping(Of String, pmodel) In dat2
            For Each d In dat
                Console.WriteLine(String.Format("key={0}, k={1}, v={2}", dat.Key, d.key, d.dat))
            Next
        Next

    End Sub
''' >>>key=AA, k=0, v=AA
''' >>>key=AA, k=1, v=AA
''' >>>key=BB, k=2, v=BB
''' >>>key=CC, k=3, v=CC
''' >>>key=DD, k=5, v=DD

コメントを投稿

Androider