Dirk Boer
Dirk Boer

Reputation: 9075

Does Linq Contains() check for HashSet?

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?

Upvotes: 14

Views: 3271

Answers (2)

Mark Hurd
Mark Hurd

Reputation: 10931

Note also it is documented to look for ICollection<T> (see Remarks).

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149030

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.

Upvotes: 19

Related Questions