D J*_*D J 35 c# linq string linq-to-objects sequences
我没有Single在LINQ下面使用,但我仍然得到一个'Sequence contains no elements'异常:
allNames = StockCollection.Where((s) => s.Name.IndexOf("A") == 0)
.Select((s) => s.Name)
.Aggregate((namesInfo, name) => namesInfo += ", " + name);
Run Code Online (Sandbox Code Playgroud)
如果没有以名称开头的库存,则会出现此异常'A'.
似乎一种扩展方法期望至少一个元素满足条件,但这不是预期的.
能否请您提出解决此问题的最佳解决方案?
提前致谢.
Ani*_*Ani 67
正如Dennis Traub指出的那样,Aggregate当源序列为空时,你的重载是使用抛出异常.
显而易见的解决方法是使用接受初始种子的其他重载Aggregate(您想要string.Empty),但这会导致结果中的前导逗号,您必须将其除去.
(编辑:你可以躲闪它,.DefaultIfEmpty(string.Empty)然后是你现有的Aggregate重载.这不会产生一个领先的逗号.)
在任何情况下,使用Aggregate这样来连接字符串并不是一个好主意(产生Schlemiel the Painter的算法).以下是我将如何编写查询:
allNames = string.Join(",", StockCollection.Select(s => s.Name)
.Where(name => name.StartsWith("A"));
Run Code Online (Sandbox Code Playgroud)
在.NET 3.5中,您需要一个.ToArray()将Where结果具体化为数组.
小智 10
使用空种子.
new string[]{}.Aggregate("", (a,b)=> a+b )
Run Code Online (Sandbox Code Playgroud)
在空源上使用Aggregate(func)会抛出InvalidOperationException.
请参阅文档:http://msdn.microsoft.com/en-us/library/bb548651.aspx
| 归档时间: |
|
| 查看次数: |
14484 次 |
| 最近记录: |