C#の概念 LINQ(クエリ結果をメモリに格納する)
ToList()
系。
成果物
情報源
コード
ToArray
, ToList
class Main { public void Run() { TestArrayAndList(); } private void TestArrayAndList() { var list = new List<int>() { 5, 1, 4, 2, 3 }; var q = from v in list where 1 == (v % 2) select v; Console.WriteLine($"ToArray: {string.Join(",", list.ToArray())}"); Console.WriteLine($"ToList: {string.Join(",", list.ToList())}"); } }
ToArray: 5,1,4,2,3 ToList: 5,1,4,2,3
ToDictionary
まずは辞書の元となるデータソースを生成する。
class Human { public string Name { get; } public int Age { get; } public Human(string name, int age) => (Name, Age) = (name, age); }
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> Query(in List<Human> humans) { return from h in humans where 1 == (h.Age % 2) select h; }
クエリ結果を辞書に変換する。
class Main { public void Run() { TestDictionary(); }
private void TestDictionary() { List<Human> humans = CreateHumans(); ShowDictionary(Query(in humans).ToDictionary(h => h.Name)); } private void ShowDictionary(in IDictionary<string, Human> dict) { foreach (KeyValuePair<string, Human> kv in dict) { Console.WriteLine($"Key={kv.Key} Value=Name:{kv.Value.Name}, Age:{kv.Value.Age}"); } }
Key=B Value=Name:B, Age:1 Key=D Value=Name:D, Age:3 Key=F Value=Name:F, Age:5
ToLookup
private void TestLookup() { List<Human> humans = CreateHumans(); ShowLookup(Query(in humans).ToLookup(h => h.Name)); } private void ShowLookup(in ILookup<string, Human> lookup) { foreach (var g in lookup) { Console.WriteLine($"Key={g.Key}"); foreach (Human h in g) { Console.WriteLine($"Name={h.Name}, Age={h.Age}"); } } }
Key=B Name=B, Age=1 Key=D Name=D, Age=3 Key=F Name=F, Age=5
ちなみに、以下だと実行時エラーになった。ILookup
にキャストできないっぽい。よくわからん。
private void ShowLookup(in ILookup<string, Human> lookup) { foreach (ILookup<string, Human> g in lookup) { Console.WriteLine($"Key={g.Key}"); foreach (Human h in g) { Console.WriteLine($"Name={h.Name}, Age={h.Age}"); } } }
System.InvalidCastException: Specified cast is not valid.
対象環境
- Raspbierry pi 3 Model B+
- Raspbian stretch 9.0 2018-11-13 ※
- bash 4.4.12(1)-release ※
- SQLite 3.29.0 ※
- C# dotnet 3.0.100 ※
$ uname -a Linux raspberrypi 4.19.42-v7+ #1218 SMP Tue May 14 00:48:17 BST 2019 armv7l GNU/Linux