Linq if list null返回null

时间:2017-06-13 14:37:55

标签: linq if-statement

我需要一种方法来添加BeveragesList!= null来模拟模型,但是如果为null则设置BeverageList = null

我尝试这样的事情:

 BeveragesList = su.Wine != null ? new List<BeverageModel>() 
 {
     new BeverageModel()
     {
         Name = su.Wine.name,
         ShortName =  su.Wine.shortName,
         Price =  su.Wine.price,
         Description = su.Wine.description,
         AlcoholContent = su.Wine.alcoholContent,
         Region =  su.Wine.Region.name,
         WineCaste =  su.Wine.wineCaste,
         UrlImageList = f.Select(i => _url+i.Image.urlImage).ToList(),
    }
}: null

我总是收到错误,我尝试了很多东西。 Soz for beeing newbieee。

1 个答案:

答案 0 :(得分:0)

基本上问题在于选择不在if语句或三元运算符中的数据 试着避免下面的事情:

AlcoholContent = su.Wine.alcoholContent,
         Region =  su.Wine.Region.name,

尝试以下代替:

your query
...
select new {
Su = su,
Wine = su.Wine,
Region = su.Wine.Region
}

然后如上所述进行选择,如下所示:

 new BeverageModel()
 {
     Name = Wine.name,
     ...