linq 中序列不包含元素异常,甚至无需使用 Single
我没有在下面的 LINQ 中使用 Single
,但我仍然收到“序列不包含元素”异常:
allNames = StockCollection.Where((s) => s.Name.IndexOf("A") == 0)
.Select((s) => s.Name)
.Aggregate((namesInfo, name) => namesInfo += ", " + name);
当没有以名称 'A'
。
似乎一种扩展方法期望至少有一个元素满足条件,但这不是预期的。
您能否建议解决此问题的最佳解决方案?
提前致谢。
I am not using Single
in LINQ below, but I am still getting a 'Sequence contains no elements' exception:
allNames = StockCollection.Where((s) => s.Name.IndexOf("A") == 0)
.Select((s) => s.Name)
.Aggregate((namesInfo, name) => namesInfo += ", " + name);
This exception comes when there is no stock starting with name 'A'
.
It seems that one extension method is expecting atleast one element satisfying the condition but that's not expected.
Can you please suggest the best solution to resolve this?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Dennis Traub 所指出的,当源序列为空时,您使用的 Aggregate 重载会引发该异常。
明显的解决方法是使用 其他重载的
Aggregate
接受初始种子(您需要string.Empty
),但这会导致结果中出现一个前导逗号,您必须将其删除。(编辑:您可以使用
.DefaultIfEmpty(string.Empty)
后跟现有的Aggregate
重载来避免这种情况。这不会产生领先的逗号。)无论如何,使用像这样的
Aggregate
来连接字符串并不是一个好主意(产生一个Schlemiel the Painter 算法)。下面是我编写查询的方法:在 .NET 3.5 中,您需要一个 .
ToArray()
将Where
结果具体化到数组中。As Dennis Traub has pointed out, the overload of
Aggregate
you are using throws that exception when the source sequence is empty.The obvious fix is to use the other overload of
Aggregate
that accepts an initial seed (you wantstring.Empty
), but that would result in a leading comma in the result which you'll have to get rid of.(EDIT: You can dodge this with
.DefaultIfEmpty(string.Empty)
followed by your existingAggregate
overload. This wouldn't produce a leading comma.)In any case, using
Aggregate
like that to join strings isn't a great idea (produces a Schlemiel the Painter's algorithm). Here's how I would write the query:In .NET 3.5, you'll need a .
ToArray()
to materialize theWhere
results into an array.与空种子一起使用。
Use with empty seed.
在空源上使用 Aggregate(func) 会引发 InvalidOperationException。
请参阅文档:http://msdn.microsoft.com/en-us/library /bb548651.aspx
Using Aggregate(func) on an empty source throws an InvalidOperationException.
See documentation: http://msdn.microsoft.com/en-us/library/bb548651.aspx