Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an item in a List<> using C#

Tags:

c#

.net

I have a list which contains a collection of objects.

How can I search for an item in this list where object.Property == myValue?

like image 824
JL. Avatar asked Sep 28 '09 07:09

JL.


People also ask

How do you check if an item is in a list C#?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How do you check if a string is present in a list of strings in C#?

bool b = listOfStrings. Any(s=>myString. Contains(s));

How do I return a string from a list in C#?

In C# you can simply return List<string> , but you may want to return IEnumerable<string> instead as it allows for lazy evaluation. @Marc: Certainly, but if you return List<string> you don't have the option even with a lazy source.

How do I search an array in C#?

Use the Array. Find() or Array. FindAll() or Array. FindLast() methods to search for an elements that match with the specified condition.


1 Answers

You have a few options:

  1. Using Enumerable.Where:

    list.Where(i => i.Property == value).FirstOrDefault();       // C# 3.0+ 
  2. Using List.Find:

    list.Find(i => i.Property == value);                         // C# 3.0+ list.Find(delegate(Item i) { return i.Property == value; }); // C# 2.0+ 

Both of these options return default(T) (null for reference types) if no match is found.

As mentioned in the comments below, you should use the appropriate form of comparison for your scenario:

  • == for simple value types or where use of operator overloads are desired
  • object.Equals(a,b) for most scenarios where the type is unknown or comparison has potentially been overridden
  • string.Equals(a,b,StringComparison) for comparing strings
  • object.ReferenceEquals(a,b) for identity comparisons, which are usually the fastest
like image 88
Drew Noakes Avatar answered Sep 27 '22 20:09

Drew Noakes