Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 排序列表抛出KeyNotFoundException_C#_Linq_Sorting - Fatal编程技术网

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

这个结构似乎满足了我的需要。非常感谢。