在列表中查找匹配项的最简洁方法
问题描述:
在列表中查找内容的最佳方法是什么?我知道 LINQ 有一些不错的技巧,但让我们也获得有关 C# 2.0 的建议.让我们为这个常见的代码模式获得最好的重构.
What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern.
目前我使用这样的代码:
Currently I use code like this:
// 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;
}
}
答
@Konrad:那你怎么用它?假设我想将 mo.ID 与 magicNumber 匹配.
@ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber.
在 C# 2.0 中你会这样写:
In C# 2.0 you'd write:
result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; });
3.0 知道 lambdas:
3.0 knows lambdas:
result = mObjList.Find(x => x.ID == magicNumber);