Does Linq streamline execution based on a real collection type?

Linq for objects works with any IEnumerable object. Variables

string[] foo = new string[] { }; 

and

 var bar = new List<string>(); 

are both IEnumerable<string> , but if I want to know how many elements each of them have, I can use the Length property in the array and the Count property in the list. Or I can use the Linq Count method, which will work for both.

The question arises: does Linq do some kind of optimization, for example, implements different algorithms for each method, calling this or that object depending on the actual type of the requested object?

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); 
+6
source share
1 answer

Answer: it depends on the Linq Count() extension method if the type implements ICollection<T> or ICollection and uses this Count property if possible, but it is not optimized for all possible scenarios.

+11
source

All Articles