Search code examples
c#linqlinq-to-sql

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;
 }

Solution

  • 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)