繁体   English   中英

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

[英]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; 
}

我正在尝试获取不为nullPlaces列表。

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

但是当PlacesCountries objectnull时,我收到一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM