在列表中查找内容的最佳方法是什么?我知道LINQ有一些不错的技巧,但我们也得到了C#2.0的建议。让我们为这个通用的代码模式获得最好的重构。
目前我使用的代码如下:
// mObjList is a List<MyObject>
MyObject match = null;
foreach (MyObject mo in mObjList)
{
if (Criteria(mo))
{
match = mo;
break;
}
}
或
// mObjList is a List<MyObject>
bool foundIt = false;
foreach (MyObject mo in mObjList)
{
if (Criteria(mo))
{
foundIt = true;
break;
}
}
答案 0 :(得分:15)
@ Konrad:你怎么用它?假设我想将mo.ID与magicNumber匹配。
在C#2.0中你会写:
result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; });
3.0知道lambdas:
result = mObjList.Find(x => x.ID == magicNumber);
答案 1 :(得分:4)
使用Lambda表达式:
List<MyObject> list = new List<MyObject>();
// populate the list with objects..
return list.Find(o => o.Id == myCriteria);
答案 2 :(得分:1)
将代码放入方法中,然后保存临时和break
(并回收代码,作为奖励):
T Find<T>(IEnumerable<T> items, Predicate<T> p) {
foreach (T item in items)
if (p(item))
return item;
return null;
}
...但当然,无论如何,这种方法已经存在于列表中,即使在.NET 2.0中也是如此。
答案 3 :(得分:1)
显然,匿名代表的表现非常重要。
测试代码:
static void Main(string[] args)
{
for (int kk = 0; kk < 10; kk++)
{
List<int> tmp = new List<int>();
for (int i = 0; i < 100; i++)
tmp.Add(i);
int sum = 0;
long start = DateTime.Now.Ticks;
for (int i = 0; i < 1000000; i++)
sum += tmp.Find(delegate(int x) { return x == 3; });
Console.WriteLine("Anonymous delegates: " + (DateTime.Now.Ticks - start));
start = DateTime.Now.Ticks;
sum = 0;
for (int i = 0; i < 1000000; i++)
{
int match = 0;
for (int j = 0; j < tmp.Count; j++)
{
if (tmp[j] == 3)
{
match = tmp[j];
break;
}
}
sum += match;
}
Console.WriteLine("Classic C++ Style: " + (DateTime.Now.Ticks - start));
Console.WriteLine();
}
}
结果:
Anonymous delegates: 710000
Classic C++ Style: 340000
Anonymous delegates: 630000
Classic C++ Style: 320000
Anonymous delegates: 630000
Classic C++ Style: 330000
Anonymous delegates: 630000
Classic C++ Style: 320000
Anonymous delegates: 610000
Classic C++ Style: 340000
Anonymous delegates: 630000
Classic C++ Style: 330000
Anonymous delegates: 650000
Classic C++ Style: 330000
Anonymous delegates: 620000
Classic C++ Style: 330000
Anonymous delegates: 620000
Classic C++ Style: 340000
Anonymous delegates: 620000
Classic C++ Style: 400000
在每种情况下,使用匿名委托比其他方式慢100%。