Linq to objects works on any IEnumerable object. The variables
string[] foo = new string[] { };
and
var bar = new List<string>();
are both IEnumerable<string>, but if I want to know how many items each one of them has, I can use Length property on the array and Count property on the list. Or I can use the Count method from Linq, which will work for both.
The question is: does Linq provides some kind of optimization, such as implement different algorithms for every method, calling one or another depending on the actual type of the object being queried?
I imagine something like this:
if (obj is Array<T>)
DoSomethingForArray(obj as Array<T>);
else if (obj is List<T>)
DoSomethingForList(obj as List<T>);
else if (obj is Collection<T>)
DoSomethingForCollection(obj as Collection<T>);
else
DoSomethingThatWorksForAnyIEnumerable(obj);
The answer is: it depends – The Linq extension method
Count()checks if the type implementsICollection<T>orICollectionand uses theCountproperty of that if possible, but it doesn’t optimize for every possible scenario.