Does it have to be inside the loop? From what you've posted, it doesn't seem to.
List<int> dummy = new List<int> {1, 2, 3, 4, 5};
if(dummy.Any())
DoJob();
int sum = 0;
foreach (int i in dummy)
sum += i;
Also, I'm assuming that snippet is just an example and not your actual code... if it is your actual code, you can use Sum
(e.g., int sum = dummy.Sum();
) instead of a foreach
loop.
I'm also assuming your actual code uses an actual List<T>
or some other concrete collection type. If it uses an IEnumerable
, then the code above will iterate through the enumerable twice, which isn't recommended. If the enumerable actually represents a database query, you'll hit the database twice. So, if that's the case, just materialize the enumerable by calling .ToList
first.