Sequence contains no elements exception in linq without even using Single

后端 未结 3 1882
轻奢々
轻奢々 2021-01-07 16:24

I am not using Single in LINQ below, but I am still getting a \'Sequence contains no elements\' exception:

allNames = StockCollection.Where((s)          


        
3条回答
  •  抹茶落季
    2021-01-07 16:33

    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 want string.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 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"));
    

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

提交回复
热议问题