Linq Contains()是否检查HashSet? [英] Does Linq Contains() check for HashSet?
问题描述
有时HashSet通过属性作为IEnumerable公开.
Sometimes a HashSet is exposed through a property as an IEnumerable.
众所周知,对于enumerable.Count()
,代码将检查它是否是一个集合,因此它不会枚举整个列表,而是采用了快捷方式.
It is well known that for enumerable.Count()
the code checks if it is a collection, so it doesn't enumerate the whole list, but takes a shortcut.
是否有使用Linq版本的enumerable.Contains(x)
和HashSets的类似检查?
Is there any similar check for using the Linq version of enumerable.Contains(x)
and HashSets?
推荐答案
来自参考源,是的,虽然不是直接的:
From the reference source, yes it does, though not directly:
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value) {
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null) return collection.Contains(value);
return Contains<TSource>(source, value, null);
}
如果源枚举实现了 ICollection<T>
(和 HashSet<T>
确实),然后它使用集合的 Contains
方法.
If the source enumerable implements ICollection<T>
(and HashSet<T>
does), then it uses the collection's Contains
method.
这篇关于Linq Contains()是否检查HashSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!