using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace gomi { class Program { static void Main(string[] args) { { Console.WriteLine("\n-------------------------> {0}", "要素列挙(基本)"); int[] a = { 1, 2, 3, 4 }; Console.WriteLine("要素数={0}", a.Count()); foreach (int s in a) Console.Write(s + ", "); } { Console.WriteLine("\n-------------------------> {0}", "ソート OrderBy"); int[] a = { 1, 4, 3, 2 }; var c = a.OrderBy(x => x); foreach (int s in c) Console.Write(s + ", "); } { Console.WriteLine("\n-------------------------> {0}", "ソート (逆順) OrderByDescending"); int[] a = { 1, 4, 3, 2 }; var c = a.OrderByDescending(x => x); foreach (int s in c) Console.Write(s + ", "); } { Console.WriteLine("\n-------------------------> {0}", "抽出 where"); int[] a = { 1, 2, 3, 4 }; Console.WriteLine("要素数={0}", a.Count(x => 0 == x % 2)); var c = a.Where(x => 0 == x % 2); foreach (int s in c) Console.Write(s + ", "); } { Console.WriteLine("\n-------------------------> {0}", "一意(重複不可)Distinct"); int[] a = { 1, 2, 2, 3 }; var c = a.Distinct(); foreach (int s in c) Console.Write(s + ", ");
} { Console.WriteLine("\n-------------------------> {0}", "連結 Concat "); int[] a = { 1, 2, 3 }; int[] b = { 3, 4, 5 }; var c = a.Concat(b); foreach (int s in c) Console.Write(s + ", "); } { Console.WriteLine("\n-------------------------> {0}", "連結 Union (一意の要素だけを返す)"); int[] a = { 1, 2, 3 }; int[] b = { 3, 4, 5 }; var c = a.Union(b); foreach (int s in c) Console.Write(s + ", "); } { Console.WriteLine("\n-------------------------> {0}", "要素を含んでいるか Contains"); int[] a = { 1, 2, 3, 4 }; Console.WriteLine("指定( 2)要素含む? {0}", a.Contains(2)); Console.WriteLine("指定(10)要素含む? {0}", a.Contains(10)); } { Console.WriteLine("\n-------------------------> {0}", "差集合(XX以外) Except"); int[] a = { 1, 2, 3 }; int[] b = { 3, 4, 5 }; var c = a.Except(b); foreach (int s in c) Console.Write(s + ", "); } { Console.WriteLine("\n-------------------------> {0}", "全ての要素が条件を満たしているか All"); int[] a = { 1, 2, 3, 4 }; Console.WriteLine("全ての要素は0より大きい? {0}", a.All(x => 0 < x)); } { Console.WriteLine("\n-------------------------> {0}", "平均 Average"); int[] a = { 1, 2, 3, 4 }; Console.WriteLine("平均={0}", a.Average()); } { Console.WriteLine("\n-------------------------> {0}", "指定keywordで2つの集合の要素を連結 join"); List<商品> a = new List<商品> { new 商品 { ID = 1, Name = "鉛筆" }, new 商品 { ID = 2, Name = "ボールペン" } }; List<金額> b = new List<金額> { new 金額 { ID = 1, Price = 100 }, new 金額 { ID = 2, Price = 200 } }; var c = a.Join(b, 商品 => 商品.ID, 金額 => 金額.ID, (商品, 金額) => new { ID = 商品.ID, Name = 商品.Name, Price = 金額.Price }); foreach (var obj in c) Console.Write(obj.ID + ": " + obj.Name + ", " + obj.Price + "\n"); } Console.Write("\n KEY入力で終了します:"); Console.ReadKey(); }
class 商品 { public int ID { get; set; } public string Name { get; set; } } class 金額 { public int ID { get; set; } public int Price { get; set; } } } } |