Linq选择新列表属性空值检查

13

我有一个如下的LINQ查询:

var productTypes = from ProductDto e in Product
                            select new 
                            {
                                Id = e.Product.ID, 
                                Name = e.Product.name 
                            };
在上面的LINQ查询中,e.Product可能为null。但我无法找到解决方法。
有人能帮帮我吗?如果e.Product为null,我想将null分配给productTypes变量。

你应该问Sunil Agrawal先生或Ajay先生 :-) - AnandMeena
使用Lambda表达式代替LINQ查询。 - Jaihind
你的意思是,“如果e.Product为空,我想在productTypes变量中赋值为null”吗?你是指如果Product为空,你希望“Id”字段为空吗?这将需要将其设置为可空int,可能会影响你的结果。 - jcharlesworthuk
3个回答

21

你可以像这样使用三元运算符来检查null

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

Ehsan,请查看更新后的问题。我想要像上面那样的输出。 - Pawan
3
这个回答应该被标记为被接受的答案,因为它展示了如何检查他想要知道的“null”值。但是这个问题也不应该被贬低,因为他的问题可以帮助其他人。 - Frank Myat Thu

4
我知道方法。我们可以使用Lambda表达式来实现:-
var productTypes = ProductList.Where(x => x.Product != null)
                              .Select(x => new 
                                          { 
                                            Id = x.Product.ID, 
                                            Name = x.Product.Name 
                                          }).ToList();

3

如果您对产品中的空值完全不感兴趣,您可以添加 where 条件。

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

如果您需要使用空值,请使用以下内容:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接