【问题标题】:Linq.Max InvalidOperationException (no elements in result) [duplicate]Linq.Max InvalidOperationException(结果中没有元素)[重复]
【发布时间】:2015-05-05 13:49:01
【问题描述】:

我有一个代码:

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);

大部分时间它都有效。但有时它会在 fulllist.Max 上抛出 InvalidOperationException。我在这里做错了什么?如果有检查 if(fulllist.Count() == 0) return 0; ?

【问题讨论】:

  • 您没有具体化您的查询,这意味着它将执行多次。也许您正在修改 Where 和 Max 之间查询的源?

标签: c# linq


【解决方案1】:

如果您查看documentation,您会发现如果输入序列为空,则会抛出InvalidOperationException。 如果它从第二行更改为第三行,这是可能的。

但无论如何我不会多次执行查询。你可以使用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;

【讨论】:

    【解决方案2】:

    为了告诉确切的错误,您应该分享更多详细信息,但您可以尝试:

    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();
    

    并且 GetCooldowns(petskills) 在任何情况下都不应该返回 null。 您应该使用 'fulllist.Any()' 而不是 'fulllist.Count() == 0' 作为一个好习惯。

    【讨论】:

      猜你喜欢
      • 2012-10-10
      • 2020-09-12
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 2017-02-10
      • 2018-04-24
      相关资源
      最近更新 更多