Linq选择新列表属性Null检查

本文关键字:属性 Null 检查 列表 选择 新列表 Linq | 更新日期: 2023-09-27 18:12:30

我有一个下面的LINQ查询:

var productTypes = from ProductDto e in Product
                            select new 
                            {
                                Id = e.Product.ID, 
                                Name = e.Product.name 
                            };

在上面的LINQ查询中,e.p product可能是null,但是我没有找到找到的方法。

有谁能帮我吗?如果e.p product是null,我想在productTypes变量中赋值null

Linq选择新列表属性Null检查

您可以使用三元运算符检查null

var productTypes = from ProductDto e in Product
                            select new 
                            {
                                Id = e.Product != null ? e.Product.ID : 0, 
                                Name = "xyz"
                            };

我明白了。我们可以使用lambda表达式:-

var productTypes = ProductList.Where(x => x.Product != null)
                              .Select(x => new 
                                          { 
                                            Id = x.Product.ID, 
                                            Name = x.Product.Name 
                                          }).ToList();

如果您对产品中的null不感兴趣,您可以添加where条件

var productTypes = from ProductDto e in Product
                        where e.Product.ID != null
                            select new 
                            {
                               Id = e.Product.ID, 
                               Name = e.Product.name 
                            };

如果您需要null,请使用以下方式:

var productTypes = Product.Select( prod => {
            if (prod.ID != null)
            {
                return new { ID = prod.ID, Name = prod.Name };
            }
            else
            {
                return null;
            }
           } );