簡體   English   中英

從 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 的 object(按分數排序)。

我在下面嘗試過,但它不起作用。 它返回相同數量的對象。

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>本質上不是有序集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM