[英]best way to check internal objects of list are null
我正在根據來自輸入的列表以及如下字符串形成一個 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
};
}
我在這里面臨不同的問題,我的庫計數為 1,但內部 object 是 null,例如在下面的圖像庫中計數為 1,它是 null,
在這種情況下,我得到了帶有上述代碼的 null 引用異常,任何人都可以幫助解決如何避免 null 異常。 提前謝謝了。
您可以在 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.