IEnumerable.包含谓词
我只需要澄清给定的集合包含一个元素。
我可以通过 collection.Count(foo => foo.Bar == "Bar") > 来做到这一点0)
但它会做不必要的工作 - 迭代整个集合,而我需要在第一次出现时停止。
但我想尝试将 Contains()
与谓词一起使用,例如 foo =>; foo.Bar ==“酒吧”
。
目前 IEnumerable
有两个签名:
IEnumerable
.Contains(T) IEnumerable
.Contains(T, IEqualityComparer ) IEnumerable
.Contains
所以我必须指定一些变量来检查:
var collection = new List<Foo>() { foo, bar };
collection.Contains(foo);
或者编写我的自定义 IEqualityComparer
它将用于我的集合:
class FooComparer : IEqualityComparer<Foo>
{
public bool Equals(Foo f1, Foo f2)
{
return (f1.Bar == f2.Bar); // my predicate
}
public int GetHashCode(Foo f)
{
return f.GetHashCode();
}
}
那么还有其他方法可以使用谓词吗?
I need just to clarify that given collection contains an element.
I can do that via collection.Count(foo => foo.Bar == "Bar") > 0)
but it will do the unnecessary job - iterate the whole collection while I need to stop on the first occurrence.
But I want to try to use Contains()
with a predicate, e.g. foo => foo.Bar == "Bar"
.
Currently IEnumerable<T>.Contains
has two signatures:
IEnumerable<T>.Contains(T)
IEnumerable<T>.Contains(T, IEqualityComparer<T>)
So I have to specify some variable to check:
var collection = new List<Foo>() { foo, bar };
collection.Contains(foo);
or write my custom IEqualityComparer<Foo>
which will be used against my collection:
class FooComparer : IEqualityComparer<Foo>
{
public bool Equals(Foo f1, Foo f2)
{
return (f1.Bar == f2.Bar); // my predicate
}
public int GetHashCode(Foo f)
{
return f.GetHashCode();
}
}
So are there any other methods to use predicate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来像你想要的;返回
bool
,一旦找到匹配就返回true
,否则返回false
。还有:其行为方式类似,一旦发现不匹配就返回
false
,否则返回true
。sounds like what you want; returns
bool
, returningtrue
as soon as a match is found, elsefalse
. There is also:which behaves in a similar way, returning
false
as soon as a non-match is found, elsetrue
.查看
IEnumerable.Any
扩展。Have a look at the
IEnumerable<T>.Any
extension.您可以使用
Any(谓词)
。它将返回 true 或 false,具体取决于谓词是否存在于某个集合中。
You can use
Any(predicate)
.It will return true or false depending if the predicate exists in a certain collection.