LINQ介绍
參考: LINQ查询主要运行操作包含:1)获取数据源;2)创建查询;3)运行查询。须要注意的是仅仅有在使用查询结果的时候才会去运行查询,或者在创建查询之后再加上tolist或者toarray之类的功能则能够马上运行。// The Three Parts of a LINQ Query: // 1. Data source. int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 }; // 2. Query creation. // numQuery is an IEnumerable var numQuery = from num in numbers where (num % 2) == 0 select num; // 3. Query execution. foreach (int num in numQuery) { Console.Write("{0,1} ", num); }
数据源能够来自于Array、List等或者直接从文件里读取的结果。
查询语句操作
參考: Filter: where cust.City==”London” && cust.Name == “Devon” Order: orderby cust.Name ascending Group: group cust by cust.City into custGroup where custGroup.Count() > 2 Join: join dist in distributors on cust.City equals dist.City其它功能
我们在使用LINQ操作的时候,往往另一些额外的需求,比方去重啊。分组啊等等。// The Three Parts of a LINQ Query: // 1. Data source. int[] numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 4 }; // 2. Query creation. // numQuery is an IEnumerable var numQuery = from num in numbers where (num % 2) == 0 select num; // 3. Query execution. foreach (int num in numQuery.Distinct()) { Console.WriteLine("{0,1} ", num); } foreach (var num in numQuery.GroupBy(key => key)) { Console.WriteLine("{0}:{1} ", num.Key, num.Count()); } foreach (int num in numQuery.GroupBy(key => key).Select(key => key.Key)) { Console.WriteLine("{0,1} ", num); }
并行处理
LINQ比較强大的是还提供了可并行处理的查询。这使得我们能够借助它来完毕一些查询或者处理的并行操作。static void Main(string[] args) { // The Three Parts of a LINQ Query: // 1. Data source. int[] numbers = new int[100]; for (var i = 0; i < 100; i++) numbers[i] = i; // 2. Query creation. // numQuery is an IEnumerable var numQuery = from num in numbers where (num % 2) == 0 select num; // 3. Query execution. Split(numQuery.ToList(), 10) .AsParallel() .WithDegreeOfParallelism(3) .Select(process) .ToList(); Console.ReadKey(); } static Tuple, int> process(Tuple
, int> input) { foreach (var num in input.Item1) Console.WriteLine("{0}-{1}", num, input.Item2); return input; } static IEnumerable
, int>> Split(List nums, int Count) { int index = 0; List num = new List (); foreach(var nm in nums) { num.Add(nm); if (num.Count >= Count) { yield return new Tuple
, int>(num, index++); num = new List (); } } if(num.Count > 0) { yield return new Tuple
, int>(num, index++); } }
具体介绍能够參考: