2017-03-29 132 views
0

我一直在處理應用程序從數據庫獲取數據到列表並對其進行排序的項目。問題在於,對於一​​種情況,需要通過可能不存在於所有項目中的密鑰來進行排序。Sorting list throws KeyNotFoundException

// The variable list is sorted into another list called sortedList 
sortedList = list.OrderBy(x => x.SomeIntegerData["key-that-is-not-in-every-item"]).ToList(); 

有些項目沒有說,「關鍵是 - 是 - 不中,每一個項目」,它會導致拋出KeyNotFoundException應用。我似乎無法將其與null或其他可能導致應用程序在密鑰不存在時執行其他操作的情況進行比較。 有沒有一種方法可以在密鑰不存在的情況下使用其他類似時間戳的東西(即保證每個項目中存在)來進行排序?

感謝

回答

0

嘗試:

// The variable list is sorted into another list called sortedList 
sortedList = list.OrderBy(x => x.SomeIntegerData.ContainsKey("key-that-is-not-in-every-item")?x.SomeIntegerData["key-that-is-not-in-every-item"]:null).ToList(); 
+0

這種結構似乎做什麼,我需要。謝謝! – VilH