创建 IEnumerable.Find()

发布于 2024-09-04 03:26:16 字数 347 浏览 10 评论 0原文

我想写:

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

我可以用扩展方法来完成这个任务吗?以下失败是因为它递归地调用自身而不是调用 IList.Find()。

public static T Find<T>(this IEnumerable<T> list, Predicate<PermitSummary> match)
{
    return list.ToList().Find(match);
}

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

往事风中埋 2024-09-11 03:26:17

这个方法已经存在了。它被称为 FirstOrDefault

cars.FirstOrDefault(car => car.Color == "Blue");

如果你自己实现它,它看起来有点像这样

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

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);
}
落叶缤纷 2024-09-11 03:26:17

如果您正在寻找一辆蓝色汽车,贾里德是正确的,任何蓝色汽车就足够了。这是您正在寻找的,还是您正在寻找蓝色汽车的列表?

第一辆蓝色汽车:

Car oneCar = cars.FirstOrDefault(c => c.Color.Equals("Blue"));

蓝色汽车列表:

IEnumerable<Car> manyCars = cars.FindAll(car => car.Color.Equals("Blue"));

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"));
笑着哭最痛 2024-09-11 03:26:17

您知道 Find(...) 可以替换为 Where / First

IEnumerable<Car> cars;
var result = cars.Where(c => c.Color == "Blue").FirstOrDefault();

如果谓词不存在,这将返回 null匹配。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文