代码之家  ›  专栏  ›  技术社区  ›  Zemprof

系统系统中出现InvalidOperationException。Linq.dll(序列不包含任何元素)

  •  1
  • Zemprof  · 技术社区  · 2 年前

    在下面的代码中出现以下异常,无法找到解决方法:

    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.Id.ToString())
                    .Aggregate( (a, b) => $"{a}, {b}" )
                    .Trim()
    

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

    2 回复  |  直到 2 年前
        1
  •  3
  •   Guru Stron    2 年前

    您可以提供种子(即初始累加器值),以便 Aggregate 不会抛出空集合(请参阅的文档 corresponding overloads )并为第一次迭代处理它。大致如下(未经测试):

    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();
    

    但我建议使用 string.Join 这应该是更完美有效的AFAIK:

    return string.Join(", ", MenuSwitchInfo?.Where(ms => ms.IsActive)
            .Select(ms => ms.Id.ToString())
        ?? Enumerable.Empty<string>());
    

    尽管这将为null和空集合返回空字符串。

        2
  •  -1
  •   vendettamit    2 年前

    可能是Aggregate方法引发了该异常。 试试这个:

    return MenuSwitchInfo == null || !MenuSwitchInfo.Any() ? null :
                    MenuSwitchInfo
                    .Where(ms => ms.IsActive)
                    .Select(ms => ms.MenuSwitchId.ToString())
                    .Aggregate( (a, b) => $"{a}, {b}" )
                    .Trim()
    
    推荐文章