在使用 SelectMany 之前空检查嵌套对象

null check nested objects before using SelectMany

我有国家列表,里面有地方列表

...

public IList<ICountriesDTO> Countries { get; set; }

 public class CountriesDTO: ICountriesDTO
 {

 public IEnumerable<IPlacesDTO> Places { get; set; 

 }

我正在尝试获取地点列表 如果不是 null

allPlacesDTO.World.Countries.SelectMany(x => x.Places == null ? null : x.Places).ToList();

但是当国家 object.

的地点为 null 时,它给出 null exception

我如何做一个 null 检查 Places 并只使用 return 语句而不是做 select 到 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();

或者把三元运算符改成returnnew List()(可以贪心)