[英]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.