首先在 Enum 上抛出 "sequence contains no elements"

First on Enum throw "sequence contains no elements"

我有后续代码:

if ( myList.Where ( .. condition .. ).Where ( .. another condition .. ).Any() )
{
     var element = myList.Where ( .. condition .. ).Where ( .. another condition .. ).First().Elements ;

     ..some logic over element ..
}

我在 IF 语句的第一行得到异常 "Sequence contains no elements"。

myList 是一个 List<MyObject>,其中 MyObject 继承自 ExpandoObject 并具有一个名为 Elements 的 getter,return 对我来说,对象是动态的。

按要求编辑我尝试获取有关在 any 和 first 中执行的查询的更多详细信息。

myList.Where ( x => x.Child.Name.Equal ( "Name" ).Where ( x => x.Elements.Value == myValue )

尝试这样的事情:

var myValue = myList.Where(..condition..).Where(..another condition..).FirstOrDefault();
if ( myValue != null )
{
     var element = myValue.Elements ;
     ..some logic over element ..
}

您使用的事实是,如果没有结果,您将得到一个空值,并检查该空值,而不是执行两次查询。此外,如果您需要更改查询,您只有一个地方可以更改它。

我想您的错误是由于前面的谓词在 .Any().First()

中略有不同造成的

你必须使用 FirstOrDefault()!

var element= myList.FirstOrDefault(x => condition1 && condition2 && ...);

if(element!= null)
{
    // Apply logic over the element
}

问题是在调用 First() 之前,没有任何内容符合您的 where 条件。鉴于您没有显示实际代码,很难判断条件是否相同,但最好的方法是像这样重写它:

var thing = myList.Where ( .. condition .. ).Where ( .. another condition .. ).FirstOrDefault();

if (thing != null)
{
    var element = thing.Element;
    ..some logic over element ..
}

这样做的好处是不会将 where 条件重复两次,并节省了输入源的双重枚举,这取决于 myList 实际是什么,可能会遭受性能损失。