Linq Select New List Property Null Check

I have the following LINQ query:

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

In the above query LINQ e.Product may be null. But I don't get a way to find out.

Can anyone help me out? I want to assign nullproductTypes in the variable if e.Product null.

+4
source share
3 answers

you can check null with the ternary operator as follows:

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

If you are not at all interested in zeros in your products, you can add a condition where

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

If you need zeros, use the following command:

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

. , : -

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

Source: https://habr.com/ru/post/1547892/


All Articles