Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq.Max InvalidOperationException(结果中没有元素)_C#_Linq - Fatal编程技术网

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