查找LINQ在列表中的项目? [英] Find an item in List by LINQ?

查看:118
本文介绍了查找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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆