Problem:
ERROR : Sequence contains no element, while using Aggregate function in LINQ
Lets see with example.
I have created AssignMe function which returns the collection of string, here is the function body.
private static string[] AssignMe()
{
return new string[] { };
}
For generating error AssignMe is returning nothing, now lets apply Aggregate function on this
string[] sList;
sList = AssignMe();
Console.Write(sList.Aggregate((first, second) => first + second));
This will throw InvalidOperationException => "Sequence contains no elements".
Lets change the AssignMe function little bit.
private static string[] AssignMe()
{
return new string[] { "NoException" };
}
This will work perfectly, and gives you output as NoException, don't get confused with NoException, Its returning result.
Solution:
We should check the item Count before applying Aggregate function, as we seen it's working well for single element. Lets put back our original AssignMe function and change the calling method.
string[] sList;
sList = AssignMe();
if (sList.Count() > 0)
Console.Write(sList.Aggregate((first, second) => first + second));
Working fine without an error :)
Conclusion:
While using Aggregate function or any other function like lamda expression or delegate; which accept argument then its better to check the Count of collection before applying such function.