Find an item in a list by LINQ

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.

Leave a Comment