In System.Linq.Dynamic.Select(), how to deal with a null object reference in a simple way?

c# dynamic-linq linq

Question

I am using dynamic LINQ (System.Linq.Dynamic)(you may find description here, http://dynamiclinq.azurewebsites.net/GettingStarted).

The following statement works well

Products.Select("new(ProductName, CategoryID.CategoryName as CategoryName)");

But I accidentally found when CategoryID is null, the results are empty. But I supposed it would return a record such as:

ProductName="Wine", CategoryName="" (or null).

Then I found a way to do so by

Products.Select("new(ProductName, iif(CategoryID==null,\"\",CategoryID.CategoryName) as CategoryName)");

The statement is ugly.

Do you have a better solution?

Thank you in advance,

1
4
5/20/2015 1:24:21 AM

Popular Answer

The only thing I found is here. It isn't clear why the solution was accepted, but what I did see there is that you can do this:

"new(ProductName, iif(CategoryID==null,null,CategoryID.CategoryName) as CategoryName)"

instead of this:

"new(ProductName, iif(CategoryID==null,\"\",CategoryID.CategoryName) as CategoryName)"

It isn't any shorter, but to me it makes the code a bit more readable because you just use null instead of escaping the quotes.

4
5/23/2017 12:16:00 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow