Create IEnumerable.Find()

后端 未结 3 1879
故里飘歌
故里飘歌 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: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(this IEnumerable enumerable, Func predicate) {
      foreach ( var current in enumerable ) {
        if ( predicate(current) ) {
          return current;
        }
      }
      return default(T);
    }
    

提交回复
热议问题