通过 LINQ 在列表中查找项目 [英] Find an item in a list by LINQ

查看:36
本文介绍了通过 LINQ 在列表中查找项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有一个简单的例子来在字符串列表中查找一个项目.通常我使用 for 循环或匿名委托来这样做:

Here I have a simple example to find an item in a list of strings. Normally I use a 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 an anonymous delegate
      string foundItem = _list.Find( delegate(string item) {
         found++;
         return string.Equals(search, item);
      });
      */
   }
   return found;
}

LINQ 对我来说是新的.我可以使用 LINQ 查找列表中的项目吗?如果可能,怎么做?

LINQ is new for me. Can I use LINQ to find an item in the list? If it is possible, how?

推荐答案

有几种方法(注意,这不是一个完整的列表).

There are a few ways (note that 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);

请注意,SingleOrDefault() 的行为是相同的,除了它会为引用类型返回 null,或者为值类型返回默认值,而不是抛出异常.

Note that SingleOrDefault() will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.

  1. 哪里返回符合您条件的所有项目,因此您可能会得到一个 IEnumerable;一个元素:

  1. Where will return all items which match your criteria, so you may get an IEnumerable<string> with one element:

 IEnumerable<string> results = myList.Where(s => s == search);

  • 首先返回符合您条件的第一项:

  • First will return the first item which matches your criteria:

     string result = myList.First(s => s == search);
    

  • 请注意,FirstOrDefault() 的行为是相同的,除了它会为引用类型返回 null,或者为值类型返回默认值,而不是抛出异常.

    Note that FirstOrDefault() will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.

    这篇关于通过 LINQ 在列表中查找项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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