Linq select with new inside和list属性throw null exceprion

时间:2016-10-07 17:09:03

标签: c# linq

美好的一天。我尝试使用linq从机构集合执行选择查询。企业包含其销售的产品列表,但产品列表可以为空。好吧,我想因为我得到null异常。我如何解决它并避免空例外? 这是我的linq查询:

var result = Establishments.Select(e => new
                {
                    ID = e.ID,
                    Name = e.Name,
                    Category = e.Category.Name,
                    XAdress = e.XAdress,
                    YAdress = e.YAdress,
                    CompanyName = e.Company.Name,
                    ProductsSelling = e.ProductsSelling.Select(p => new // error here
                    {
                        ID = p.ID,
                        Name = p.Name,
                        Category = p.Category.Name,
                        Price = p.Price,
                        Additives = p.PossibleAdditives.Select(a => new
                        {
                            ID = a.ID,
                            Name = a.Name,
                            Price = a.Price
                        })
                    })                    
                });

1 个答案:

答案 0 :(得分:3)

在使用Null-Conditional Operator查询ProductsSelling之前,您可以检查它是否为null:

var result = Establishments.Select(e => new
            {
                ID = e.ID,
                Name = e.Name,
                Category = e.Category.Name,
                XAdress = e.XAdress,
                YAdress = e.YAdress,
                CompanyName = e.Company.Name,
                ProductsSelling = e.ProductsSelling?.Select(p => new /* note the '?' operator*/
                {
                    ID = p.ID,
                    Name = p.Name,
                    Category = p.Category.Name,
                    Price = p.Price,
                    Additives = p.PossibleAdditives.Select(a => new
                    {
                        ID = a.ID,
                        Name = a.Name,
                        Price = a.Price
                    })
                })                    
            });

如果e.ProductsSelling不为null,它将执行linq查询,否则它将返回null,这将阻止您获得NullReferenceException。