JL.
JL.

Reputation: 81272

Finding an item in a List<> using C#

I have a list which contains a collection of objects.

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

Upvotes: 72

Views: 198234

Answers (6)

Drew Noakes
Drew Noakes

Reputation: 310907

You have a few options:

  1. Using Enumerable.Where and Enumerable.FirstOrDefault:

     list.Where(i => i.Property == value).FirstOrDefault();       // C# 3.0+
    
  2. Using Enumerable.FirstOrDefault on its own:

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

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

All 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

Upvotes: 171

Todd Davis
Todd Davis

Reputation: 6035

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

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

Upvotes: 1

abelenky
abelenky

Reputation: 64682

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.

Upvotes: 29

Jonas Elfström
Jonas Elfström

Reputation: 31428

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

Upvotes: 2

eric
eric

Reputation: 1887

For .NET 2.0:

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

Upvotes: 0

shahkalpesh
shahkalpesh

Reputation: 33474

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

Upvotes: 10

Related Questions