创建 IEnumerable.Find()
我想写:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个方法已经存在了。它被称为 FirstOrDefault
如果你自己实现它,它看起来有点像这样
This method already exists. It's called FirstOrDefault
If you were to implement it yourself it would look a bit like this
如果您正在寻找一辆蓝色汽车,贾里德是正确的,任何蓝色汽车就足够了。这是您正在寻找的,还是您正在寻找蓝色汽车的列表?
第一辆蓝色汽车:
蓝色汽车列表:
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:
List of blue cars:
您知道
Find(...)
可以替换为Where / First
如果谓词不存在,这将返回
null
匹配。You know that
Find(...)
can be replaced byWhere / First
This'll return
null
in the event that the predicate doesn't match.