Create IEnumerable.Find()

后端 未结 3 1885
故里飘歌
故里飘歌 2021-02-07 01:39

I\'d like to write:

IEnumerable cars;
cars.Find(car => car.Color == \"Blue\")

Can I accomplish this with extension methods? The f

相关标签:
3条回答
  • 2021-02-07 02:06

    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 讨论(0)
  • 2021-02-07 02:09

    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);
    }
    
    0 讨论(0)
  • 2021-02-07 02:26

    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"));
    
    0 讨论(0)
提交回复
热议问题