C#の学習 No. 10 LINQ
LINQといってもSQLを操作するのではなく、オブジェクトの操作。
ソート機能が強すぎる。たいていはDB相手なのでいいけど、オブジェクトに対してSQLと同様の構文でソートができるのは強烈すぎる。文法の見た目はアレだけど、最近の開発者はSQLは知っているしそんなに違和感なく使えそう。見た目も含めて強烈。
まずサンプル。
using System.Collections.Generic; using System.Linq; namespace Sample { public class LinqTest { public static void Main(string[] args) { List<Player> list = new List<Player>(); list.Add(new Player("18", 23, 20000, "涌井", "わくい")); list.Add(new Player("60", 26, 18000, "中村", "なかむら")); list.Add(new Player("70", 22, 1000, "中村", "なかむら")); list.Add(new Player("3", 27, 25000, "中島", "なかじま")); System.Console.WriteLine("***** ソート前"); foreach (Player p in list) { p.Print(); } var sortList1 = from temp in list orderby temp.Sebango select temp; System.Console.WriteLine("***** 背番号でソート"); foreach (Player p in sortList1) { p.Print(); } var sortList2 = from temp in list orderby temp.KanaName, temp.Money select temp; System.Console.WriteLine("***** かな名、年俸順にソート"); foreach (Player p in sortList2) { p.Print(); } var sortList3 = from temp in list orderby temp.KanaName, temp.Money descending select temp; System.Console.WriteLine("***** かな名、年俸順の逆順にソート"); foreach (Player p in sortList3) { p.Print(); } } } public class Player { public Player(string sebango, int age, int money, string name, string kanaName) { Sebango = sebango; Age = age; Money = money; Name = name; KanaName = kanaName; } public void Print() { System.Console.WriteLine(Sebango + " : " + Age + " : " + Money + " : " + Name + " : " + KanaName); } public string Sebango { get; set; } public int Age { get; set; } public int Money { get; set; } public string Name { get; set; } public string KanaName { get; set; } } }
実行結果
***** ソート前 18 : 23 : 20000 : 涌井 : わくい 60 : 26 : 18000 : 中村 : なかむら 70 : 22 : 1000 : 中村 : なかむら 3 : 27 : 25000 : 中島 : なかじま ***** 背番号でソート 18 : 23 : 20000 : 涌井 : わくい 3 : 27 : 25000 : 中島 : なかじま 60 : 26 : 18000 : 中村 : なかむら 70 : 22 : 1000 : 中村 : なかむら ***** かな名、年俸順にソート 3 : 27 : 25000 : 中島 : なかじま 70 : 22 : 1000 : 中村 : なかむら 60 : 26 : 18000 : 中村 : なかむら 18 : 23 : 20000 : 涌井 : わくい ***** かな名、年俸順の逆順にソート 3 : 27 : 25000 : 中島 : なかじま 60 : 26 : 18000 : 中村 : なかむら 70 : 22 : 1000 : 中村 : なかむら 18 : 23 : 20000 : 涌井 : わくい 続行するには何かキーを押してください . . .
すごい。