今天在家看了一下linq,實踐了一下書中代碼,發現排序和查重的先後順序太重要了。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LinqLearning { class Program { private static int[] GenerateLotsOfNumbers(int count) { Random generator = new Random(0); int[] result = new int[count]; for (int i = 0; i < count; i++) { result[i] = generator.Next(); } return result; } static void Main(string[] args) { int[] numbers = GenerateLotsOfNumbers(12345678); var queryResults = from n in numbers where n < 1000 orderby n descending select n; Console.WriteLine("查詢語法排序結果:"); DateTime start = DateTime.Now; foreach (var item in queryResults) Console.WriteLine(item); Console.WriteLine("消耗時間:{0}",DateTime.Now-start); var queryResult = numbers.OrderByDescending(n => n).Where(n => n < 1000); Console.WriteLine("方法排序結果(排序字段在前):"); start = DateTime.Now; foreach (var item in queryResult) Console.WriteLine(item); Console.WriteLine("消耗時間:{0}", DateTime.Now - start); var query = numbers.Where(n => n < 1000).OrderByDescending(n => n); Console.WriteLine("方法排序結果(排序字段在後):"); start = DateTime.Now; foreach (var item in query) Console.WriteLine(item); Console.WriteLine("消耗時間:{0}", DateTime.Now - start); Console.ReadKey(); } } }