やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

C#の概念 LINQ(入れ子になったグループ)

 副問合せ(サブクエリ)。

成果物

情報源

コード

class Human {
    public string Name { get; }
    public int Age { get; }
    public Human(string name, int age) => (Name, Age) = (name, age);
}
class Main {
    public void Run() {
        List<Human> humans = CreateHumans();
        Show(Query(humans));
    }
    private List<Human> CreateHumans() {
        return new List<Human> {
            new Human("A", 0), new Human("A", 1),
            new Human("B", 2), new Human("A", 3),
            new Human("B", 4), new Human("B", 5),
        };
    }
    private IEnumerable<IGrouping<string, IGrouping<bool, Human>>> Query(in List<Human> humans) {
        return from h in humans
               group h by h.Name into g1
               from g2 in (
                from h in g1
                group h by 0 == (h.Age % 2)
               )
               group g2 by g1.Key;
    }
    private void Show(in IEnumerable<IGrouping<string, IGrouping<bool, Human>>> groups) {
        foreach (var g1 in groups) {
            Console.WriteLine($"Key1={g1.Key}");
            foreach (var g2 in g1) {
                Console.WriteLine($"  Key2=年齢が偶数か:{g2.Key}");
                foreach (var v in g2) {
                    Console.WriteLine($"    Value=Name:{v.Name}, Age:{v.Age}");
                }
            }
        }
    }
}
Key1=A
  Key2=年齢が偶数か:True
    Value=Name:A, Age:0
  Key2=年齢が偶数か:False
    Value=Name:A, Age:1
    Value=Name:A, Age:3
Key1=B
  Key2=年齢が偶数か:True
    Value=Name:B, Age:2
    Value=Name:B, Age:4
  Key2=年齢が偶数か:False
    Value=Name:B, Age:5

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux