Finding an item in a List<> using C#

C#.Net

C# Problem Overview


I have a list which contains a collection of objects.

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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

What is wrong with List.Find ??

I think we need more information on what you've done, and why it fails, before we can provide truly helpful answers.

Solution 3 - C#

var myItem = myList.Find(item => item.property == "something");

Solution 4 - C#

item = objects.Find(obj => obj.property==myValue);

Solution 5 - C#

list.FirstOrDefault(i => i.property == someValue); 

This is based on Drew's answer above, but a little more succinct.

Solution 6 - C#

For .NET 2.0:

list.Find(delegate(Item i) { return i.Property == someValue; });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJL.View Question on Stackoverflow
Solution 1 - C#Drew NoakesView Answer on Stackoverflow
Solution 2 - C#abelenkyView Answer on Stackoverflow
Solution 3 - C#shahkalpeshView Answer on Stackoverflow
Solution 4 - C#Jonas ElfströmView Answer on Stackoverflow
Solution 5 - C#Todd DavisView Answer on Stackoverflow
Solution 6 - C#ericView Answer on Stackoverflow