C# 排序列表抛出KeyNotFoundException
我一直在从事一个项目,在这个项目中,应用程序将数据从数据库获取到一个列表,并对其进行排序。问题是,在一种情况下,排序需要由一个键完成,该键可能不存在于所有项中C# 排序列表抛出KeyNotFoundException,c#,linq,sorting,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(); 有些项没有“
// 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或在密钥不存在时使应用程序执行其他操作的东西进行比较。
当密钥不存在时,是否有其他方法使用时间戳(保证存在于每个项中)来进行排序
谢谢试试:
// 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();
这个结构似乎满足了我的需要。非常感谢。