やってみる

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

C#の概念 LINQ(オブジェクト)

 LINQ to Object。

成果物

情報源

 前回まではデータソースがint[]などであった。今回は独自クラスのコレクションである。

コード

 適当な独自型をつくる。

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();
        Shows(Query0(in humans));
    }
    private List<Human> CreateHumans() {
        return new List<Human> {
            new Human("A", 0),
            new Human("B", 1),
            new Human("C", 2),
            new Human("D", 3),
            new Human("E", 4),
            new Human("F", 5),
        };
    }
    private IEnumerable<Human> Query0(in List<Human> humans) {
        return from h in humans
               where 1 == (h.Age % 2)
               select h;
    }
    private void Shows(in IEnumerable<Human> humans) {
        foreach (var h in humans) {
            Console.WriteLine($"name={h.Name}, age={h.Age}");
        }
    }
}

 実行結果は以下。

name=B, age=1
name=D, age=3
name=F, age=5

対象環境

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