描述:项目中使用了linq,发现写的顺序不同最后的结果也不同,效率也不同。html
List<int> source = new List<int>(); var rand = new Random(); int i = 5000; while (i > 0) { i--; source.Add(rand.Next(1, 500)); } Stopwatch watch = new Stopwatch(); watch.Restart(); var temp2 = from s in source orderby s where s > 100 select s; int count2 = temp2.Count(); watch.Stop(); Console.WriteLine("orderby s where s > 100: " + watch.ElapsedTicks); watch.Restart(); var temp1 = from s in source where s > 100 orderby s select s; int count = temp1.Count(); watch.Stop(); Console.WriteLine("where s > 100 orderby s: " + watch.ElapsedTicks);
效果如图:sql
效率相差仍是蛮大的,差很少10倍,因此linq的执行要按照必定的顺序,不能为所欲为。dom
linq和sql的语法差很少,因此能够按照sql的执行顺序对linq进行优化,建议顺序优化
1.FROM
2.join 3.WHERE
4.GROUP BY
5.ORDER BY
6.SELECT
https://www.cnblogs.com/zhao123/p/5621841.htmlspa