[英]IEnumerable<T>.Contains with predicate
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. 我可以通过
collection.Count(foo => foo.Bar == "Bar") > 0)
来做到这一点,但它会做不必要的工作 - 迭代整个集合,而我需要在第一次出现时停止。
But I want to try to use Contains()
with a predicate, eg foo => foo.Bar == "Bar"
. 但我想尝试将
Contains()
与谓词一起使用,例如foo => foo.Bar == "Bar"
。
Currently IEnumerable<T>.Contains
has two signatures: 目前
IEnumerable<T>.Contains
有两个签名:
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: 或编写我的自定义
IEqualityComparer<Foo>
,它将用于我的收藏:
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? 那么有没有其他方法可以使用谓词?
.Any(predicate)
sounds like what you want; 听起来像你想要的; returns
bool
, returning true
as soon as a match is found, else false
. 返回
bool
,一找到匹配就返回true
,否则返回false
。 There is also: 还有:
.All(predicate)
which behaves in a similar way, returning false
as soon as a non-match is found, else true
. 其行为方式类似,一旦找到不匹配就返回
false
,否则为true
。
You can use Any(predicate)
. 您可以使用
Any(predicate)
。 It will return true or false depending if the predicate exists in a certain collection. 它将返回true或false,具体取决于谓词是否存在于某个集合中。
看一下IEnumerable<T>.Any
扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.