2009-11-09 75 views
6

我有我嘗試綁定到列表視圖的對象列表。我正在排序的兩個屬性。存在的問題是某些記錄可能沒有其中一個屬性。這是造成錯誤。我希望它仍然綁定有屬性的記錄。或檢查lambda表達式中的屬性是否爲空

IEnumerable<ERec> list = retailerList.Cast<ERec>(); 
lvwRetailStores.DataSource = list.OrderByDescending(r => r.Properties["RS_Partner Type"].ToString()) 
           .ThenBy(r => r.Properties["RS_Title"].ToString()); 
+0

你想記錄丟失屬性是在排序列表的開始或結束? – outis

回答

7
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()); 

,而不是!= null,則使用任何測試屬性集合了。

0

你可以在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

我應該注意到,一旦lambda開始得到這麼長時間,無論如何宣佈它們是清理代碼的函數是一個好主意。 – Serguei

0

另一種常見的方法是給收集合適的默認值,並返回時,集合不具有特定的鍵。舉例來說,如果Properties實現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()); 
1

我發現了?運營商運作良好。我使用括號評估空,

例如:

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

同樣的邏輯適用於LAMBDA,只需用括號,以確保正確的比較中使用。