No, maybe the other way around. If it is not a collection (such as List or Array ), but a pending executed query, it must be executed completely, which can be very expensive, just to determine the counter. In your example, this is actually List , Enumerable.Count smart enough to first transfer it to ICollection<T> / ICollection . If this succeeds, the Count property is used.
So just use foreach . It doesn’t hurt if the sequence is empty, the cycle will be immediately deleted.
For the same reason, it is better to use Enumerable.Any instead of Count() > 0 if you just want to check if the sequence contains at least one element. The goal is also more clear.
Tim schmelter
source share