开发者

Create IEnumerable<T>.Find()

开发者 https://www.devze.com 2023-01-02 18:14 出处:网络
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 re开发者_如何学编程cursively

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 re开发者_如何学编程cursively 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消