Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Find an item in a list by LINQ

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 is new for me. Can I use LINQ to find an item in the list? If it is possible, how?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

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

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

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. 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);
    
  2. First will return the first item which matches your criteria:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...