佐々木屋

技術的なことから趣味まで色々書きます

GroupByメソッド②

GroupByメソッドには複合キーを指定することも可能です。複合キーの指定の仕方は2通りあり、new(VB.NETはNew With)による匿名型で指定する方法とTuple.Createで指定する方法があります。

List<Uriage> lst = new List<Uriage>() {
                    new Uriage{KaisyaCD="1",SyainCD = "25",UriageSu = 5, UriageKingaku=3000},
                    new Uriage{KaisyaCD="1",SyainCD = "31",UriageSu = 10, UriageKingaku=4000},
                    new Uriage{KaisyaCD="2",SyainCD = "31",UriageSu = 98, UriageKingaku=12800},
                    new Uriage{KaisyaCD="1",SyainCD = "25",UriageSu = 11, UriageKingaku=250}
                };

//new
var res = lst.GroupBy(x => new { x.KaisyaCD, x.SyainCD });

//Tuple.Create
var res = lst.GroupBy(x => Tuple.Create(x.KaisyaCD, x.SyainCD));

foreach (var r1 in res) {
    Console.WriteLine(r1.Key);
    foreach (var r2 in r1) {
        Console.WriteLine(r2.UriageSu);
    }
}

VB.NETのNew Withの場合は、匿名型に対してKeyキーワードをつけないと集計されません。

Dim lst As New List(Of Uriage) From {
                    New Uriage With {.KaisyaCD = "1", .SyainCD = "25", .UriageSu = 5, .UriageKingaku = 3000},
                    New Uriage With {.KaisyaCD = "1", .SyainCD = "31", .UriageSu = 10, .UriageKingaku = 4000},
                    New Uriage With {.KaisyaCD = "2", .SyainCD = "31", .UriageSu = 98, .UriageKingaku = 12800},
                    New Uriage With {.KaisyaCD = "1", .SyainCD = "25", .UriageSu = 11, .UriageKingaku = 250}
                }

'New With
Dim res = lst.GroupBy(Function(x) New With {Key x.KaisyaCD, Key x.SyainCD})

'Tuple.Create
Dim res = lst.GroupBy(Function(x) Tuple.Create(x.KaisyaCD, x.SyainCD))

For Each r1 In res
    Console.WriteLine(r1.Key)
    For Each r2 In r1
        Console.WriteLine(r2.UriageSu)
    Next
Next
{ KaisyaCD = 1, SyainCD = 25 }
5
11
{ KaisyaCD = 1, SyainCD = 31 }
10
{ KaisyaCD = 2, SyainCD = 31 }
98