【问题标题】:best way to check internal objects of list are null检查列表内部对象的最佳方法为空
【发布时间】:2021-06-15 06:46:49
【问题描述】:

我正在根据来自输入的列表以及如下字符串形成一个对象。

public static LibrarySourceTableInput CreateLibrarySourceTableInput<T>(List<T> libraries, string mechanicalLibraryName)
    where T : ISourceOfData
{
    return new LibrarySourceTableInput()
    {
        LibrarySourceRowInputs = libraries?.Select(l => new LibrarySourceRowInput()
        {
            LibrarySourceId = l.Id,
            SourceOfDataId = l.SourceOfData.Id
        }).ToList() ?? new(),
        MappedLibrarySource = mechanicalLibraryName
    };        
}

我在这里面临不同的问题,我的库计数为 1,但内部对象为空,例如在下面的图像库中计数为 1,它为空,

在这种情况下,我在上面的代码中得到了一个空引用异常,任何人都可以帮助解决如何避免该空异常。非常感谢。

【问题讨论】:

    标签: c# .net linq c#-6.0


    【解决方案1】:

    您可以在选择之前进行 where 查询。

    LibrarySourceRowInputs = libraries?.Where(l => l != null)
                                       .Select(l => l => new LibrarySourceRowInput()
                                                  {
                                                   LibrarySourceId = l.Id,
                                                   SourceOfDataId = l.SourceOfData.Id
                                                  }).ToList() ?? new();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多