从 C# 中的字典值中排序并取 N
Sort and Take N from dictionary value in C#
我有一本 C# 字典。
Dictionary originalMap = new Dictionary<string, List<CustomObject>>();
originalMap contents:
"abc" -> {CustomObject1, CustomeObject2, ..CustomObject100};
"def" -> {CustomObject101,CustomObject102, CustomObject103};
现在,最后我想确保上面所有客户对象的数量不超过限制 - 比如 200。
在执行此操作时,我想确保获得排名前 200 的对象(按分数排序)。
我在下面尝试过,但没有用。它 returns 个相同数量的对象。
var modifiedMap = new Dictionary<string, IList<CustomObject>>(CustomObject);
modifiedMap = originalMap.OrderByDescending(map => map.Value.OrderByDescending(customObject => customObject.Score).ToList().Take(200))
.ToDictionary(pair => pair.Key, pair => pair.Value);
如有任何帮助,我们将不胜感激。
谢谢。
您只是在进行排序时执行限制部分 - 而不是在您实际创建新词典时。
听起来你想要这样的东西:
var modifiedMap = originalMap.ToDictionary(
pair => pair.Key,
pair => pair.Value.OrderByDescending(co => co.Score).Take(200).ToList());
请注意,对字典条目本身进行排序是没有意义的,因为 Dictionary<TKey, TValue>
本质上不是一个有序的集合。
我有一本 C# 字典。
Dictionary originalMap = new Dictionary<string, List<CustomObject>>();
originalMap contents:
"abc" -> {CustomObject1, CustomeObject2, ..CustomObject100};
"def" -> {CustomObject101,CustomObject102, CustomObject103};
现在,最后我想确保上面所有客户对象的数量不超过限制 - 比如 200。 在执行此操作时,我想确保获得排名前 200 的对象(按分数排序)。
我在下面尝试过,但没有用。它 returns 个相同数量的对象。
var modifiedMap = new Dictionary<string, IList<CustomObject>>(CustomObject);
modifiedMap = originalMap.OrderByDescending(map => map.Value.OrderByDescending(customObject => customObject.Score).ToList().Take(200))
.ToDictionary(pair => pair.Key, pair => pair.Value);
如有任何帮助,我们将不胜感激。 谢谢。
您只是在进行排序时执行限制部分 - 而不是在您实际创建新词典时。
听起来你想要这样的东西:
var modifiedMap = originalMap.ToDictionary(
pair => pair.Key,
pair => pair.Value.OrderByDescending(co => co.Score).Take(200).ToList());
请注意,对字典条目本身进行排序是没有意义的,因为 Dictionary<TKey, TValue>
本质上不是一个有序的集合。