先说需求:找出一个对象List中,某个属性值最大的对象。
1.定义对象
1 private class A 2 { 3 public int ID { get; set; } 4 5 public string Name { get; set; } 6 }
1 private static TimeSpan compare = new TimeSpan(); 2 private static TimeSpan order = new TimeSpan();
1 private static void MaxByOrder(List<A> list) 2 { 3 DateTime start = DateTime.Now; 4 A max = list.OrderByDescending(i => i.ID).First(); 5 TimeSpan span = DateTime.Now - start; 6 order += span; 7 Console.WriteLine(max.Name + " Order:" + span); 8 }
1 private static void Max(List<A> list) 2 { 3 DateTime start = DateTime.Now; 4 int maxID = list.Max(m => m.ID); 5 A max = list.First(i => i.ID == maxID); 6 TimeSpan span = DateTime.Now - start; 7 compare += span; 8 Console.WriteLine(max.Name + " Compare:" + span); 9 }
1 private static void Main(string[] args) 2 { 3 List<A> list = new List<A>(); 4 list = Enumerable.Range(1, 10000000).Select(n => new A { ID = n, Name = n.ToString() }).ToList(); 5 Console.WriteLine("print"); 6 int i = 0; 7 while (i < 100) 8 { 9 MaxByOrder(list); 10 Max(list); 11 i++; 12 } 13 Console.WriteLine("Compare:" + compare); 14 Console.WriteLine("Order:" + order); 15 Console.ReadLine(); 16 }
6.查看运行结果:
首先两种方式都找到了最大值,用第一种方式基本上花费时间为第二种的四到五倍。
ok,今天就先到这,希望大家拍砖……
原文:http://www.cnblogs.com/codedoing/p/4645196.html