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.
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"
                            };
                        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;
            }
           } );
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With