C# LINQ サンプル2
概要
ソースコード
/* * LINQ で遊ぶ * 2014 / 12 / 05 * jskny / risdy.net */ using System; using System.Linq; class Test { public static int Main() { // 売上データベース // id, name, お気に入り登録数, 買われた数 var Database = new[] { new { id = 1, name = "つけ麺", fav = 1, bought = 53 }, new { id = 2, name = "タンメン", fav = 10, bought = 641 }, new { id = 3, name = "イケメン", fav = 30, bought = 42 }, new { id = 4, name = "ラーメン", fav = 400, bought = 42 }, new { id = 5, name = "ぽよ麺", fav = 400, bought = 869 }, new { id = 6, name = "ぽぽぽ~ん", fav = 20, bought = 1630 }, new { id = 7, name = "塩ラーメン", fav = 8, bought = 352 }, new { id = 8, name = "味噌ラーメン", fav = 90, bought = 6885 }, new { id = 9, name = "お寿司", fav = 3, bought = 35 } }; // 全要素出力 System.Console.WriteLine("VIEW ALL DB."); foreach (object t in Database) { System.Console.WriteLine(t); } // 500回以上買われた商品名のみ出力 System.Console.WriteLine("VIEW OVER 500 BOUGHT."); var boughtUp500 = from t in Database where t.bought >= 500 orderby t.id select t.name; foreach (var t in boughtUp500) { System.Console.WriteLine(t); } // 500回以上買われた商品名をお気に入り登録数の少ない順に整列 System.Console.WriteLine("VIEW OVER 500 BOUGHT AND Orderby FAV."); var boughtUp500odFav = from t in Database where t.bought >= 500 orderby t.fav select t.name; foreach (var t in boughtUp500odFav) { System.Console.WriteLine(t); } // 500回以上買われた商品名をお気に入り登録数の多い順に整列 System.Console.WriteLine("VIEW OVER 500 BOUGHT AND Orderby FAV descending."); var boughtUp500odFavNum = from t in Database where t.bought >= 500 orderby t.fav descending select t.name; foreach (var t in boughtUp500odFavNum) { System.Console.WriteLine(t); } return (0); } }
コンソール
VIEW ALL DB. { id = 1, name = つけ麺, fav = 1, bought = 53 } { id = 2, name = タンメン, fav = 10, bought = 641 } { id = 3, name = イケメン, fav = 30, bought = 42 } { id = 4, name = ラーメン, fav = 400, bought = 42 } { id = 5, name = ぽよ麺, fav = 400, bought = 869 } { id = 6, name = ぽぽぽ~ん, fav = 20, bought = 1630 } { id = 7, name = 塩ラーメン, fav = 8, bought = 352 } { id = 8, name = 味噌ラーメン, fav = 90, bought = 6885 } { id = 9, name = お寿司, fav = 3, bought = 35 } VIEW OVER 500 BOUGHT. タンメン ぽよ麺 ぽぽぽ~ん 味噌ラーメン VIEW OVER 500 BOUGHT AND Orderby FAV. タンメン ぽぽぽ~ん 味噌ラーメン ぽよ麺 VIEW OVER 500 BOUGHT AND Orderby FAV descending. ぽよ麺 味噌ラーメン ぽぽぽ~ん タンメン
感想
意外と便利