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 implements ICollection<T>
or ICollection
and uses the Count
property of that if possible, but it doesn't optimize for every possible scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With