If I do the something like the following with LINQ:
void DoSomeStuffWithHashSet()
{
HashSet<int> set = new HashSet<int>();
for (int i = 0; i < 100; ++i) set.Add(i);
if (Lookup(set, new Random().NextInt(200))
System.Console.WriteLine("Yey");
else
System.Console.WriteLine("Ney");
}
bool Lookup(IEnumerable<int> haystack, int needle)
{
// O(N) search or HashSet<int>.Contains()?
return Enumerable.Contains(collection, needle);
}
Will Enumerable.Contains() resolve to the optimized implementation on HashSet or will a simple search be performed regardless of the input?
Yes, it will use
HashSet<T>.Contains.HashSet<T>implementsICollection<T>and per the documentation forEnumerable.Contains:always, Always, ALWAYS check the documentation!