查找LINQ在列表中的项目? [英] Find an item in List by LINQ?
问题描述
在这里,我有一个简单的例子来查找字符串列表中的项目。通常情况下我使用的循环或匿名委托去做这样的:
Here I have a simple example to find an item in a list of strings. Normally I use for loop or anonymous delegate to do it like this:
int GetItemIndex(string search)
{
int found = -1;
if ( _list != null )
{
foreach (string item in _list) // _list is an instance of List<string>
{
found++;
if ( string.Equals(search, item) )
{
break;
}
}
/* use anonymous delegate
string foundItem = _list.Find( delegate(string item) {
found++;
return string.Equals(search, item);
});
*/
}
return found;
}
LINQ是新的我。我很好奇,如果我可以使用LINQ在列表中找到项目?如何如果可能的话?
LINQ is new for me. I am curious if I can use LINQ to find item in list? How if possible?
推荐答案
有几个方法(注意,这是的不的完整列表)。
There's a few ways (note this is not a complete list).
1) 单 会返回一个结果,但如果发现没有或一个以上的将抛出一个异常(这可能是也可能不是你想要的):
1) Single will return a single result, but will throw an exception if it finds none or more than one (which may or may not be what you want):
string search = "lookforme";
List<string> myList = new List<string>();
string result = myList.Single(s => s == search);
2)的其中, 将返回匹配所有的项目标准,所以你可能会得到一个IEnumerable一个元素:
2) Where will return all items which match your criteria, so you may get an IEnumerable with one element:
IEnumerable<string> results = myList.Where(s => s == search);
3)的首页 将返回匹配的第一个项目您的标准:
3) First will return the first item which matches your criteria:
string result = myList.First(s => s == search);
这篇关于查找LINQ在列表中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!