前言
簡介:LINQ,語言集成查詢(Language INtegrated Query)是一組用於c#和Visual Basic語言的擴展。
分類:LINQ to Object, LINQ to XML, LINQ to SQL, LINQ to DataSet,LINQ to ADO.NET。
相關:相信linq大家已經很熟悉了,如果有不太熟的,可以參考MSDN 地址:http://msdn.microsoft.com/zh-cn/library/bb397933.aspx
緣由:Linq 到底能不能用?究竟好不好用,很多時候大家還是眾說紛紜,有人迷茫,有人觀望,有人覺得無所謂,或者還有人說只是語法糖,中看不中用,哪我們這個系列就為大家揭開謎團。首先來看LINQ to Object在數組篩選方面的效率測試吧。
實例分析
測試環境:visual studio 2011 Beta(netframework 4.0+)C# 控制台程序
測試需求:從10000000條數據中查詢大於100的數據。
核心代碼(LINQ):
var linqList = from num in list1 where num > 100 select num;
完整代碼:
/// <summary> /// 效率測試 /// </summary> /// <param name="testCount">第幾次測試</param> private static void timeTest(int testCount) { const int listCount = 10000000; // 數組長度 Random random = new Random(); // 數據隨機構建值 // 數組構建 List<int> listData = new List<int>(); for (int i = 0; i < listCount; i++) { listData.Add(random.Next(10000)); } // LINQ 測試 Stopwatch linq_Stopwatch = new Stopwatch(); linq_Stopwatch.Start(); var linqList = from num in listData where num > 100 select num; var linqCount = linqList.Count(); linq_Stopwatch.Stop(); // 普通方式 測試 Stopwatch before_Stopwatch = new Stopwatch(); before_Stopwatch.Start(); List<int> beforeList = new List<int>(listCount); for (int i = 0; i < listData.Count(); i++) { if (listData[i] > 100) beforeList.Add(listData[i]); } var beforeCount = beforeList.Count; before_Stopwatch.Stop(); // 打印結果 Console.WriteLine(String.Format("第{0}次測試,測試:{5}條數據。\n\r \t LINQ用時:{1}毫秒,篩選了{2}條數據。\n\r\t 普通用時:{3}毫秒,篩選了{4}條數據。\r\n", testCount, linq_Stopwatch.ElapsedMilliseconds, linqCount, before_Stopwatch.ElapsedMilliseconds, beforeCount, listCount)); }
結果
結論:由此可知LINQ to Object在做數據處理,效率要好於手動判斷,當然LINQ偉大應該是她的語法簡潔與優雅。在做數據處理時個人推薦使用LINQ to Object!