Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

c# - 在LINQ中找到List中的项目?(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:

(通常我使用for循环或匿名委托来这样做:)

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 is new for me.

(LINQ对我来说是新的。)

I am curious if I can use LINQ to find item in list?

(我很好奇我是否可以使用LINQ来查找列表中的项目?)

How if possible?

(怎么可能?)

  ask by David.Chu.ca translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a few ways (note this is not a complete list).

(有几种方法(注意这不是一个完整的清单)。)

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):

(1) Single将返回一个结果,但如果找不到或多于一个(可能是你想要的或不是你想要的),将抛出异常:)

string search = "lookforme";
List<string> myList = new List<string>();
string result = myList.Single(s => s == search);

Note 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.

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

2) Where will return all items which match your criteria, so you may get an IEnumerable with one element:

(2) 哪里将返回符合您条件的所有项目,因此您可以获得一个元素的IEnumerable:)

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

3) First will return the first item which matches your criteria:

(3) 首先将返回符合您标准的第一项:)

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

Note 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...