序列包含在LINQ任何元素例外,甚至没有使用单 [英] Sequence contains no elements exception in linq without even using Single

查看:169
本文介绍了序列包含在LINQ任何元素例外,甚至没有使用单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不使用在下面LINQ,但我仍然得到一个序列不包含任何元素的异常:

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

这异常来时,有没有股票开头的名字'A'

This exception comes when there is no stock starting with name 'A'.

看来,一个扩展方法需要ATLEAST一个元素满足条件,但是这不是预期的。

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?

先谢谢了。

推荐答案

丹尼斯·特劳布曾指出,当源序列为空总结您使用的过载抛出异常。

As Dennis Traub has pointed out, the overload of Aggregate you are using throws that exception when the source sequence is empty.

最明显的解决方法是使用其他超载的总结接受初始种子(您想的String.Empty ),但是这会导致在这你必须摆脱的结果,一个领先的逗号。

The obvious fix is to use the other overload of Aggregate that accepts an initial seed (you want string.Empty), but that would result in a leading comma in the result which you'll have to get rid of.

修改:您可以使用<$ C $躲过此C> .DefaultIfEmpty(的String.Empty)其次是现有的总结超载。这不会产生一个领先的逗号。)

(EDIT: You can dodge this with .DefaultIfEmpty(string.Empty) followed by your existing Aggregate 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:

allNames = string.Join(",", StockCollection.Select(s => s.Name)
                                           .Where(name => name.StartsWith("A"));

在.NET 3.5,你需要一个 ToArray的()来兑现的其中,成果转化阵列

In .NET 3.5, you'll need a .ToArray() to materialize the Where results into an array.

这篇关于序列包含在LINQ任何元素例外,甚至没有使用单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆