I want to use List.Find() on a simple collection that does not implement Find().
The naive way I thought of, is to just wrap it with a list and execute .Find(), like this:
ICollection myCows = GetAllCowsFromFarm(); // whatever the collection impl. is...
var steak = new List<Cow>(myCows).Find(moo => moo.Name == "La Vache qui Rit");
Now, 1st of all I’d like to know, C#-wise, what is the cost of this wrapping?
Is it still faster to ‘for’ this collection the traditional way?
Second, is there a better straightforward way elegantly use that .Find()?
Cheers!
List<T>, when constructed with anIEnumerable(i.e. yourICollection), copies the content. This could be expensive.Do you have LINQ available? If so, you can use the
Firstextension method, which returns the first match found (or throws an exception if there’s no match). This will work on anyIEnumerable<T>:You can also use
Where, which will return all the matches:There’s a heap of useful extension methods in the
Enumerableclass. LINQ is not just for databases.