Let’s say I have some code:
var items = ItemsGetter.GetAllItems().Where(x => x.SomeProperty > 20);
int sum1 = items.Sum(x => x.SomeFlag == true);
And for example I need some other sum from the items collection later in the code.
int sum2 = items.Sum(x => x.OtherFlag == false);
So my question: Is it OK to call Linq methods on IEnumerable more than once? Maybe I should call Reset() method on enumerator or make list from items using ToList method?
Well, it really depends what you want to do. You could take the hit of executing the query twice (and the exact meaning of that will depend on what
GetAllItems()does), or you could take the hit of copying the results to a list:Once it’s in a list, obviously it’s not a problem to iterate over that list multiple times.
Note that you can’t call
Resetbecause you don’t have the iterator – you have theIEnumerable<T>. I wouldn’t recommend callingIEnumerator<T>in general anyway – many implementations (including any generated by the C# compiler from iterator blocks) don’t actually implementResetanyway (i.e. they throw an exception).