Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Linq Contains() check for HashSet?

Tags:

c#

linq

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?

like image 610
Dirk Boer Avatar asked Aug 12 '14 22:08

Dirk Boer


2 Answers

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.

like image 195
p.s.w.g Avatar answered Sep 28 '22 10:09

p.s.w.g


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

like image 27
Mark Hurd Avatar answered Sep 28 '22 10:09

Mark Hurd