Bilal Issa
Bilal Issa

Reputation: 67

How to use List<T>.Find() on a simple collection that does not implement Find()?

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!

Upvotes: 1

Views: 684

Answers (4)

Bilal Issa
Bilal Issa

Reputation: 67

I'll just add to you guys the use of .FirstOrDefault() to avoid exception, WDYT?

Upvotes: 0

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

You can use linq for this:

using System.Linq;

...

var steak = myCows.First(moo => moo.Name == "La Vache qui Rit"); 

Upvotes: 0

Roger Lipscombe
Roger Lipscombe

Reputation: 91855

List<T>, when constructed with an IEnumerable (i.e. your ICollection), copies the content. This could be expensive.

Do you have LINQ available? If so, you can use the First extension method, which returns the first match found (or throws an exception if there's no match). This will work on any IEnumerable<T>:

var cattle = GetAllCows();
var steak = cattle.First(moo => moo.Name == "La Vache qui Rit");

You can also use Where, which will return all the matches:

var cattle = GetAllCows();
var matches = cattle.Where(moo => moo.Name == "La Vache qui Rit");

There's a heap of useful extension methods in the Enumerable class. LINQ is not just for databases.

Upvotes: 4

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

Use Enumerable.Where:

var steak = myCows.Where(moo => moo.Name == "La Vache qui Rit");

This has the advantage of not costing you a complete copy of the collection.

EDIT: D'oh! @Roger's answer is better.

Upvotes: 1

Related Questions