Search code examples
c#linqsortingtake

Sort and Take N from dictionary value in C#


I have a dictionary in C#.

Dictionary originalMap = new Dictionary<string, List<CustomObject>>();

originalMap contents: 
"abc" -> {CustomObject1, CustomeObject2, ..CustomObject100};
"def" -> {CustomObject101,CustomObject102, CustomObject103};

Now, finally I want to make sure that the count of all custome objects above does not exceed a limit - say 200. While doing this, I want to make sure that I take top 200 ranked object (sorted by Score porperty).

I tried below but it doesn't work. It returns same number of objects.

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

Any help will be appreciated. Thank you.


Solution

  • You're only performing the limit part while doing the ordering - not when you actually create the new dictionary.

    It sounds like you want something like:

    var modifiedMap = originalMap.ToDictionary(
        pair => pair.Key,
        pair => pair.Value.OrderByDescending(co => co.Score).Take(200).ToList());
    

    Note that ordering the dictionary entries themselves would be pointless, as Dictionary<TKey, TValue> is inherently not an ordered collection.