Microsoft Developer Network > Forums Home > Archived Forums Forums > LINQ Project General > Aggregate ... Sequence contains no elements
Ask a questionAsk a question
 

AnswerAggregate ... Sequence contains no elements

  • Thursday, November 05, 2009 3:06 AMmpaulf Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hello,
    Using Aggregate on an empty list throws a "Sequence contains no elements" exception, so I was wondering if it was possible to somehow force the following snippet of code to return an empty string or perhaps null if there are no elements in my list:

    String descriptions = sourceList.ToList()
                                    .Select(item => item.Description)
                                    .Distinct()
                                    .Aggregate((previous, next) => String.Concat(previous, ","
    
    , next));
    
    I suppose I could split the code above in two statements, one that would select the distinct descriptions I'm interested in into a list and then checking whether there are any elements in it before calling Aggregate, but I'm using similar statements in a few different places, so if possible it would be ideal to do it in one.

    EDIT: I forgot to mention that my solution for now was to add an extension method that checks whether sourceList is empty and if it isn't it calls the Aggregate, otherwise it returns null, which I suppose is a decent solution, but I'm still wondering if there is another way.

    Thanks

Answers

All Replies