简体   繁体   English

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

[英]null check nested objects before using SelectMany

I have list of Countries and inside it have list of Places .我有Countries列表,里面有Places列表。

// ...

public IList<ICountriesDTO> Countries { get; set; }
public class CountriesDTO: ICountriesDTO
{
    public IEnumerable<IPlacesDTO> Places { get; set; 
}

I am trying to get list of Places that are not null .我正在尝试获取不为nullPlaces列表。

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

But I receive a null exception when Places are null for their Countries object .但是当PlacesCountries objectnull时,我收到一个null exception

How can I do a null check for Places and just use return statement instead of doing select to null object , similar to what I have below?如何对Places进行null检查,只使用return语句而不是 select to null object ,类似于我下面的内容?

  if (allPlacesDTO.World.Countries.Places == null)
  {
      return;
  }

Update:更新:

My requirement was if there is no places in any of the countries just use the return statement to exit the current function without proceeding further.我的要求是,如果任何国家/地区都没有地方,只需使用return语句退出当前功能而不继续进行。 That was achieved by the accepted answer and Count function.这是通过接受的答案和Count功能实现的。

 var lstAllPlaces = allPlacesDTO.World.Countries
    .Where(x => x.Places != null)
    .SelectMany(x => x.Places)
    .ToList();

 if (lstAllPlaces.Count() == 0)
 {
     return;
 }

You can do the condition in where clause您可以在 where 子句中执行条件

allPlacesDTO.World.Countries.Where(x => x.Places != null)
                            .SelectMany(x => x.Places).ToList();

Or change the ternary operator to return new List() (it can be greedy)或者更改三元运算符以返回 new List() (它可能是贪婪的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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