[英]NUnit: Should I check that objects are not null before using them in asserts?
[英]null check nested objects before using SelectMany
我有Countries
列表,里面有Places
列表。
// ...
public IList<ICountriesDTO> Countries { get; set; }
public class CountriesDTO: ICountriesDTO
{
public IEnumerable<IPlacesDTO> Places { get; set;
}
我正在嘗試獲取不為null
的Places
列表。
allPlacesDTO.World.Countries
.SelectMany(x => x.Places == null ? null : x.Places)
.ToList();
但是當Places
的Countries
object
為null
時,我收到一個null exception
。
如何對Places
進行null
檢查,只使用return
語句而不是 select to null object
,類似於我下面的內容?
if (allPlacesDTO.World.Countries.Places == null)
{
return;
}
我的要求是,如果任何國家/地區都沒有地方,只需使用return
語句退出當前功能而不繼續進行。 這是通過接受的答案和Count
功能實現的。
var lstAllPlaces = allPlacesDTO.World.Countries
.Where(x => x.Places != null)
.SelectMany(x => x.Places)
.ToList();
if (lstAllPlaces.Count() == 0)
{
return;
}
您可以在 where 子句中執行條件
allPlacesDTO.World.Countries.Where(x => x.Places != null)
.SelectMany(x => x.Places).ToList();
或者更改三元運算符以返回 new List() (它可能是貪婪的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.