Check if property is null in lambda expression

I have a list of objects that I am trying to associate with listview. I sort by two properties. The problem is that some records may not have one of the properties. This causes an error. I would like him to still bind property records.

IEnumerable<ERec> list = retailerList.Cast<ERec>(); lvwRetailStores.DataSource = list.OrderByDescending(r => r.Properties["RS_Partner Type"].ToString()) .ThenBy(r => r.Properties["RS_Title"].ToString()); 
+6
c # lambda listview
source share
4 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 any tag that has a collection of properties.

+7
source share

I found that the Operator is working well. I use Parenthesis to evaluate for null,

Example:

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

The same logic works in Lambda, just use parentheses to make sure that the correct comparisons are used.

+1
source share

You can use triple expression in lambda:

 list.OrderByDescending(r => r.Properties["RS_Partner_Type"] == null ? null : r.Properties["RS_Partner Type"].ToString()) .ThenBy(r => r.Properties["RS_Title"] == null ? null : r.Properties["RS_Title"].ToString()); 
0
source share

Another common approach is to provide the collection with a suitable default value and return it when the collection does not have a specific key. For example, if Properties implements IDictionary,

 public static class IDictionaryExtension { public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue default) { TValue result; return dict.TryGetValue(key, out result) ? result : dflt; } } ... lvwRetailStores.DataSource = list.OrderByDescending(r => r.GetValue("RS_Partner Type", "").ToString()) .ThenBy(r => r.GetValue("RS_Title","").ToString()); 
0
source share

All Articles