Getting the following exception in the code below and cannot figure out how to solve for it:
Exception thrown: 'System.InvalidOperationException' in System.Linq.dll Sequence contains no elements
The code is:
return MenuSwitchInfo?
.Where(ms => ms.IsActive)
.Select(ms => ms.Id.ToString())
.Aggregate( (a, b) => $"{a}, {b}" )
.Trim();
I've also tried the following with no luck:
return MenuSwitchInfo?
.DefaultIfEmpty()
.Where(ms => ms.IsActive)
.Select(ms => ms.Id.ToString())
.Aggregate( (a, b) => $"{a}, {b}" )
.Trim()
MenuSwitchInfo is an ObservableCollection. Any ideas on how to solve for this?
Check exceptions section of the docs for the Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)
:
InvalidOperationException
source
contains no elements.
i.e. for empty collection this overload will result in corresponding exception.
You can provide the seed (i.e. initial accumulator value) so Aggregate
will not throw for empty collections (see the docs for corresponding overloads) and handle it for the first iteration. Something along these lines (not tested):
return MenuSwitchInfo?
.Where(ms => ms.IsActive)
.Select(ms => ms.Id.ToString()) // also you can remove this select and handle the transform in the Aggregate
.Aggregate((string)null, (a, b) => a is null ? b : $"{a}, {b}");
?.Trim();
But I would recommend to use string.Join
which should be more perfromance effective AFAIK:
return string.Join(", ", MenuSwitchInfo?.Where(ms => ms.IsActive)
.Select(ms => ms.Id.ToString())
?? Enumerable.Empty<string>());
Though this will return empty string for both null and empty collections.