sto*_*tom 0 c# linq linq-to-sql
我有国家列表,里面有地方列表
...
public IList<ICountriesDTO> Countries { get; set; }
public class CountriesDTO: ICountriesDTO
{
public IEnumerable<IPlacesDTO> Places { get; set;
}
Run Code Online (Sandbox Code Playgroud)
我想获取地方列表如果没有 null
allPlacesDTO.World.Countries.SelectMany(x => x.Places == null ? null : x.Places).ToList();
Run Code Online (Sandbox Code Playgroud)
但它给出的null exception地方是null为国家object.
我如何null检查Places并只使用return语句而不是选择null object,如下所示?
if (allPlacesDTO.World.Countries.Places == null)
{
return;
}
Run Code Online (Sandbox Code Playgroud)
更新:
我的要求是,如果在任何一个国家没有地方只使用return声明退出当前功能而不继续进行.这是通过公认的答案和Count功能实现的.
var lstAllPlaces = allPlacesDTO.World.Countries.Where(x => x.Places != null).SelectMany(x => x.Places).ToList();
if (lstAllPlaces.Count() == 0)
{
return;
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家的答案.欣赏.
你可以在where子句中执行条件
allPlacesDTO.World.Countries.Where(x => x.Places != null)
.SelectMany(x => x.Places).ToList();
Run Code Online (Sandbox Code Playgroud)
或者更改三元运算符以返回新的List()(它可以是贪心的)