Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
 }
like image 861
Shaiju T Avatar asked Jun 04 '26 21:06

Shaiju T


1 Answers

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)

like image 118
Cedric Avatar answered Jun 07 '26 11:06

Cedric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!