C# Linq排序
今天在家看了一下linq,实践了一下书中代码,发现排序和查重的先后顺序太重要了。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace LinqLearning 7 { 8 class Program 9 { 10 private static int[] GenerateLotsOfNumbers(int count) 11 { 12 Random generator = new Random(0); 13 int[] result = new int[count]; 14 for (int i = 0; i < count; i++) 15 { 16 result[i] = generator.Next(); 17 } 18 return result; 19 } 20 21 static void Main(string[] args) 22 { 23 int[] numbers = GenerateLotsOfNumbers(12345678); 24 25 var queryResults = from n in numbers 26 where n < 1000 27 orderby n descending 28 select n; 29 Console.WriteLine("查询语法排序结果:"); 30 DateTime start = DateTime.Now; 31 foreach (var item in queryResults) 32 Console.WriteLine(item); 33 Console.WriteLine("消耗时间:{0}",DateTime.Now-start); 34 35 var queryResult = numbers.OrderByDescending(n => n).Where(n => n < 1000); 36 Console.WriteLine("方法排序结果(排序字段在前):"); 37 start = DateTime.Now; 38 foreach (var item in queryResult) 39 Console.WriteLine(item); 40 Console.WriteLine("消耗时间:{0}", DateTime.Now - start); 41 42 var query = numbers.Where(n => n < 1000).OrderByDescending(n => n); 43 Console.WriteLine("方法排序结果(排序字段在后):"); 44 start = DateTime.Now; 45 foreach (var item in query) 46 Console.WriteLine(item); 47 Console.WriteLine("消耗时间:{0}", DateTime.Now - start); 48 49 Console.ReadKey(); 50 } 51 } 52 }