问题
Sometimes a HashSet is exposed through a property as an IEnumerable.
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.
Is there any similar check for using the Linq version of enumerable.Contains(x)
and HashSets?
回答1:
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);
}
If the source enumerable implements ICollection<T> (and HashSet<T> does), then it uses the collection's Contains method.
回答2:
Note also it is documented to look for ICollection<T>
(see Remarks).
来源:https://stackoverflow.com/questions/25275071/does-linq-contains-check-for-hashset