Linq select with new inside和list属性抛出null异常

本文关键字:属性 null 异常 list select with new inside Linq | 更新日期: 2023-09-27 18:12:00

大家好。我试图执行选择查询与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
                        })
                    })                    
                });

Linq select with new inside和list属性抛出null异常

在使用空条件运算符查询之前,您可以检查ProductsSelling是否为空:

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.p productsselling不是null,它将执行linq查询,否则它将返回null,这将防止NullReferenceException你正在得到