System.Linq.dll 中的“System.InvalidOperationException”(序列不包含元素)

问题描述 投票:0回答:1

在下面的代码中出现以下异常,并且无法弄清楚如何解决它:

Exception thrown: 'System.InvalidOperationException' in System.Linq.dll 

Sequence contains no elements

代码是:

        return MenuSwitchInfo?
                .Where(ms => ms.IsActive)
                .Select(ms => ms.Id.ToString())
                .Aggregate( (a, b) => $"{a}, {b}" )
                .Trim();

我也尝试过以下方法,但没有成功:

        return MenuSwitchInfo?
                .DefaultIfEmpty()
                .Where(ms => ms.IsActive)
                .Select(ms => ms.MenuSwitchId.ToString())
                .Aggregate( (a, b) => $"{a}, {b}" )
                .Trim()

MenuSwitchInfo 是一个 ObservableCollection。 关于如何解决这个问题有什么想法吗?

c# .net linq exception uwp
1个回答
0
投票

您可以提供默认聚合器状态并在第一次迭代时处理它:

return MenuSwitchInfo?
    .Where(ms => ms.IsActive)
    .Select(ms => ms.Id.ToString()) // also you can remove this select
    .Aggregate((string)null, (a, b) => a is null ? b : $"{a}, {b}");
    .Trim();

但我建议使用

string.Join
,这应该更有效 AFAIK:

return string.Join(", ", MenuSwitchInfo?.Where(ms => ms.IsActive)
        .Select(ms => ms.Id.ToString())
    ?? Enumerable.Empty<string>());
© www.soinside.com 2019 - 2024. All rights reserved.