I'd like to write:
IEnumerable<Car> cars;
cars.Find(car => car.Color == "Blue")
Can I accomplish this with extension methods? The following fails because it recursively calls itself rather than calling IList.Find().
public static T Find<T>(this IEnumerable<T> list, Predicate<PermitSummary> match)
{
return list.ToList().Find(match);
}
Thanks!
IEnumerable interface is a generic interface which allows looping over generic or non-generic lists. IEnumerable interface also works with linq query expression. IEnumerable interface Returns an enumerator that iterates through the collection.
IEnumerable is a deferred execution while List is an immediate execution. IEnumerable will not execute the query until you enumerate over the data, whereas List will execute the query as soon as it's called. Deferred execution makes IEnumerable faster because it only gets the data when needed.
What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");
We can get first item values from IEnumerable list by using First() property or loop through the list to get respective element. IEnumerable list is a base for all collections and its having ability to loop through the collection by using current property, MoveNext and Reset methods in c#, vb.net.
This method already exists. It's called FirstOrDefault
cars.FirstOrDefault(car => car.Color == "Blue");
If you were to implement it yourself it would look a bit like this
public static T Find<T>(this IEnumerable<T> enumerable, Func<T,bool> predicate) {
foreach ( var current in enumerable ) {
if ( predicate(current) ) {
return current;
}
}
return default(T);
}
Jared is correct if you are looking for a single blue car, any blue car will suffice. Is that what you're looking for, or are you looking for a list of blue cars?
First blue car:
Car oneCar = cars.FirstOrDefault(c => c.Color.Equals("Blue"));
List of blue cars:
IEnumerable<Car> manyCars = cars.FindAll(car => car.Color.Equals("Blue"));
You know that Find(...)
can be replaced by Where / First
IEnumerable<Car> cars;
var result = cars.Where(c => c.Color == "Blue").FirstOrDefault();
This'll return null
in the event that the predicate doesn't match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With