Thanks for help with explaining to me about IList and IEnumerable. I have marked that question as answered. Now I have a request for just a bit more information.
I have code like this:
for (var index = 0; index < Model.Items.Count(); index++)
It was suggested in a previous post that it’s not efficient as the Count() is a method and it gets executed many times. I tried the following:
for (var index = 0; index < Model.Items.Count; index++)
This seems to work.
Can someone please confirm there’s a difference. Both work so I am not 100 % sure.
Would the following be the most efficient? Does the foreach need an IList or and IEnumerable?
foreach(var item in Items)
The
Count()method call actually calls the staticEnumerable.Count()method. This is optimized forIListimplementations to use the property – but this requires a dynamic type check, and still ends up going through to the property – so using the property is certainly more efficient. In .NET 3.5 it only optimizes forICollection<T>, whereas in .NET 4 it optimizes for the non-genericICollectionas well. See my Edulinq blog post onCountfor more details.As for the last bit of your question: a
foreachloop may or may not be more efficient, but it would be more readable in my view, which is rather more important. I would definitely useforeachunless you really need the index of each entry.