描述:項目中使用了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