排序列表抛出KeyNotFoundException

时间:2017-03-29 19:43:29

标签: c# linq sorting

我一直致力于一个项目,在这个项目中,应用程序将数据从数据库获取到列表并对其进行排序。问题是,对于一种情况,排序需要通过一个可能不存在于所有项目中的密钥来完成。

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

某些项目没有“key-that-not-in-every-item”,它会导致应用程序抛出KeyNotFoundException。我似乎无法将它与null或可能使应用程序在密钥不存在时执行其他操作的内容进行比较。 有没有办法使用其他东西,如时间戳(保证存在于每个项目中),以便在密钥不存在时进行排序?

由于

1 个答案:

答案 0 :(得分: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();