I have a list which contains a collection of objects.
How can I search for an item in this list where object.Property == myValue?
object.Property == myValue
You have a few options:
Using Enumerable.Where:
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
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.
default(T)
null
As mentioned in the comments below, you should use the appropriate form of comparison for your scenario:
==
object.Equals(a,b)
string.Equals(a,b,StringComparison)
object.ReferenceEquals(a,b)
1.4m articles
1.4m replys
5 comments
57.0k users