Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if property is null in lambda expression

I have a list of objects that I am trying to bind to a listview. I am sorting by two properties. The problem exists whereby some records may not have one of the properties. This is causing an error. I would like it to still bind the records that have the property.

IEnumerable<ERec> list = retailerList.Cast<ERec>();
lvwRetailStores.DataSource = list.OrderByDescending(r => r.Properties["RS_Partner Type"].ToString())
                                 .ThenBy(r => r.Properties["RS_Title"].ToString());
like image 849
mickyjtwin Avatar asked Nov 09 '09 01:11

mickyjtwin


2 Answers

list.Where(r => r.Properties["RS_Partner_Type"] != null && r.Properties["RS_Title"] != null)
    .OrderByDescending(r => r.Properties["RS_Partner Type"].ToString())
    .ThenBy(r => r.Properties["RS_Title"].ToString());

Or instead of != null, use whatever test the Properties collection has.

like image 144
Adam Ruth Avatar answered Nov 03 '22 02:11

Adam Ruth


I've found that the ?? Operator works well. I use Parenthesis to evaluate for null,

For Example:

Datetime? Today = DateTimeValue // Check for Null, if Null put Today's date datetime GoodDate = Today ?? DateTime.Now

This same logic works in Lambda, just use parenthesis to ensure that the correct comparisons are used.

like image 23
hiramknick Avatar answered Nov 03 '22 00:11

hiramknick