簡體   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