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

时间:2018-03-16 09:57:20

标签: c# linq linq-to-sql

我有国家列表,里面有地方列表

dataSource.setUrl("jdbc:h2:mem:cpq_testdb;INIT=create schema if not exists my_database\\;runscript from '**classpath:scripts/create.sql**';DB_CLOSE_DELAY=-1");

我正在尝试获取地方列表,如果不是use my_database; create schema if not exists your_schema_name;

...

public IList<ICountriesDTO> Countries { get; set; }

 public class CountriesDTO: ICountriesDTO
 {

 public IEnumerable<IPlacesDTO> Places { get; set; 

 }

但是当国家null的地点为allPlacesDTO.World.Countries.SelectMany(x => x.Places == null ? null : x.Places).ToList(); 时,它会为null exception提供。

如何对地点进行null检查,只使用object声明,而不是选择null,如下所示?

return

更新

我的要求是,如果任何国家/地区都没有地方只使用null object语句退出当前功能而不继续进行。这是通过接受的答案和 if (allPlacesDTO.World.Countries.Places == null) { return; } 函数实现的。

return

谢谢大家的回答。欣赏。

1 个答案:

答案 0 :(得分:5)

您可以在where子句

中执行该条件
allPlacesDTO.World.Countries.Where(x => x.Places != null)
                            .SelectMany(x => x.Places).ToList();

或者更改三元运算符以返回新的List()(它可以是贪婪的)