假设要在Datatable中选出符合要求的一串数据,可以有Foreach循环、Linq语句和Select语句几种方法,构造一个简单数据后做了下效率对比,发现Linq最慢,其次Foreach,最快是Select。
代码如下:
static void Main(string[] args) { int dataCount = 100000; DataTable dt = new DataTable(); dt.Columns.Add("MacID", typeof(int)); dt.Columns.Add("DevID"); DataColumn[] keys = new DataColumn[1]; keys[0] = dt.Columns[0]; dt.PrimaryKey = keys; for (int i = 0; i < dataCount; i++) { DataRow dr = dt.NewRow(); dr["MacID"] = i; dr["DevID"] = dataCount - i; dt.Rows.Add(dr); } long startTick; long stopTick; // Foreach int filterCount = 0; startTick = DateTime.Now.Ticks; foreach (DataRow item in dt.Rows) { if ((int)item[0] > 200) { filterCount++; } } Console.WriteLine("ID > 200: " + filterCount); stopTick = DateTime.Now.Ticks; Console.WriteLine("Foreach " + (stopTick - startTick)); // Linq startTick = DateTime.Now.Ticks; var newList = (from item in dt.AsEnumerable() where item.Field<int>(0) > 200 select item).ToList(); Console.WriteLine("ID > 200: " + newList.Count); stopTick = DateTime.Now.Ticks; Console.WriteLine("LINQ " + (stopTick - startTick)); // SELECT startTick = DateTime.Now.Ticks; var filterResult = dt.Select("MacID > 200"); Console.WriteLine("ID > 200: " + filterResult.Count()); stopTick = DateTime.Now.Ticks; Console.WriteLine("SELECT " + (stopTick - startTick)); Console.ReadLine(); }
运行后得到如下结果:
Foreach 120014
LINQ 340026
SELECT 79994
SELECT效率最高,但具体也得看数据表是如何建立索引的,不同的索引对搜索结果有较大影响,LINQ效率居然低于Foreach,这是挺意外的,目前并不清除为什么会比Foreach更加耗时。
时间: 2024-10-10 08:55:01