C# Linq.Max InvalidOperationException(结果中没有元素)
我有一个密码:C# Linq.Max InvalidOperationException(结果中没有元素),c#,linq,C#,Linq,我有一个密码: 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()
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);
var fullist=Enumerable.Where(GetCooldowns(petskills),s=>(spellId.Contains((uint)s.spellId)| |(SharedIds.Contains((uint)s.SharedId)&&s.SharedId!=0))&&s.TimeLeft>0);
if(fullist.Count()==0)返回0;
返回fullist.Max(s=>s.TimeLeft);
大多数情况下,它是有效的。但有时它会在fullist.Max上抛出invalidoOperationException。我做错了什么?如果检查(fullist.Count()==0)是否返回0;,则fullist怎么可能为空 如果查看,您会发现如果输入序列为空,则会引发InvalidOperationException
。
如果它从第二行变为第三行,这是可能的
但无论如何,我不会多次执行查询。您可以使用DefaultIfEmpty(0)
要准确告知错误,您应该分享更多详细信息,但您可以尝试:
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。
最好使用“fullist.Any()”而不是“fullist.Count()==0”。您没有具体化查询,这意味着它将执行多次。也许您正在修改要在
Where
和Max
之间查询的源代码?
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();