ICollection - Get single value

Udo Weber picture Udo Weber · Dec 12, 2008 · Viewed 101.4k times · Source

What is the best way to get a value from a ICollection? We know the Collection is empty apart from that.

Answer

user1228 picture user1228 · Dec 12, 2008

Linq, baby, yeah...

   var foo = myICollection.OfType<YourType>().FirstOrDefault();
    // or use a query
    var bar = (from x in myICollection.OfType<YourType>() where x.SomeProperty == someValue select x)
       .FirstOrDefault();