2

I have a code:

var fullist =  Enumerable.Where<CooldownRecord>(GetCooldowns(petskills), s => (spellId.Contains((uint)s.SpellId) || (SharedIds.Contains((uint)s.SharedId) && s.SharedId != 0)) && s.TimeLeft > 0);
if(fullist.Count() == 0) return 0;
return fullist.Max(s => s.TimeLeft);

Most of the time it works. But sometimes it throws InvalidOperationException on fullist.Max. What am I doing wrong here? How can the fullist be empty if there is a check if(fullist.Count() == 0) return 0; ?

CodeDemen
  • 1,841
  • 3
  • 17
  • 30
  • 5
    You aren't materializing your query, which means it will execute multiple times. Perhaps you're modifying the source you're querying between the `Where` and `Max`? – Yuval Itzchakov May 05 '15 at 13:51

2 Answers2

4

If you look at the documentation you'll find out that an InvalidOperationException is thrown if the input sequence is empty. That's possible if it changes from the second to the third line.

But i wouldn't execute the query more than once anyway. You can use DefaultIfEmpty(0)

int maxTimeLeft = GetCooldowns(petskills)
    .Where(s => (spellId.Contains((uint)s.SpellId) || SharedIds.Contains((uint)s.SharedId)) && s.SharedId != 0)) && s.TimeLeft > 0)
    .Select(s => s.TimeLeft)
    .DefaultIfEmpty(0)
    .Max();
return maxTimeLeft;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

For telling exact error, you should share more details but you can try:

return GetCooldowns(petskills).Where(s => (spellId.Contains((uint)s.SpellId) || (SharedIds.Contains((uint)s.SharedId) && s.SharedId != 0)) && s.TimeLeft > 0).Select(x => s.TimeLeft)
                     .DefaultIfEmpty(0)
                     .Max();

And GetCooldowns(petskills) should not return null in any case. And you should use 'fullist.Any()' instead of 'fullist.Count() == 0' as a good practice.

ATP
  • 553
  • 1
  • 3
  • 16