简体   繁体   English

检查列表内部对象的最佳方法是 null

[英]best way to check internal objects of list are null

I am forming an object based on list coming from input along with the string like as below.我正在根据来自输入的列表以及如下字符串形成一个 object。

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
    };        
}

I am facing different problem here, I have libraries count coming as 1 but internal object is null for example in the below image libraries count as 1 and it is null,我在这里面临不同的问题,我的库计数为 1,但内部 object 是 null,例如在下面的图像库中计数为 1,它是 null,

在此处输入图像描述

and in this case I am getting a null reference exception with the above code, could any one please help on this how to avoid that null exception.在这种情况下,我得到了带有上述代码的 null 引用异常,任何人都可以帮助解决如何避免 null 异常。 Many thanks in advance.提前谢谢了。

You could do a where query before the select.您可以在 select 之前进行 where 查询。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM