Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create IEnumerable<T>.Find()

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!

like image 447
Brian Low Avatar asked Jun 03 '10 20:06

Brian Low


People also ask

What is IEnumerable T in C#?

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.

What's the difference between IEnumerable T and list t?

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.

How do I add items to an IEnumerable list?

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");

How do I find the value of an IEnumerable list?

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.


3 Answers

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);
}
like image 181
JaredPar Avatar answered Oct 18 '22 02:10

JaredPar


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"));
like image 30
StyxRiver Avatar answered Oct 18 '22 02:10

StyxRiver


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.

like image 4
Aren Avatar answered Oct 18 '22 01:10

Aren