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?
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.
Note also it is documented to look for ICollection<T>
(see Remarks).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With