简体   繁体   中英

null check nested objects before using SelectMany

I have list of Countries and inside it have list of 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 .

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 .

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?

  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. That was achieved by the accepted answer and Count function.

 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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