Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Select New List Property Null Check

Tags:

c#

null

linq

I have a below LINQ query :

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

In the above LINQ query the e.Product may be null.But I am not getting the way to find out.

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

like image 906
Pawan Avatar asked Jul 10 '14 11:07

Pawan


2 Answers

you can check for null using ternary operator like this:

var productTypes = from ProductDto e in Product
                            select new 
                            {
                                Id = e.Product != null ? e.Product.ID : 0, 
                                Name = "xyz"
                            };
like image 70
Ehsan Sajjad Avatar answered Nov 14 '22 15:11

Ehsan Sajjad


If you are not interesting in nulls in your products at all, you can add where condition

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

In case you need your nulls, please use following:

var productTypes = Product.Select( prod => {
            if (prod.ID != null)
            {
                return new { ID = prod.ID, Name = prod.Name };
            }
            else
            {
                return null;
            }
           } );
like image 3
Anton Semenov Avatar answered Nov 14 '22 14:11

Anton Semenov