Andeverien Andeverien - 2 months ago 11
C# Question

How to sort a nested Collection by its objects modified value?

Basically I have an object as follows:

IDictionary<string, ICollection<KeyValuePair<string, int>>> myDict;


What I'd like to do is to sort its inner collections by keys without underscore prefixes they have.

My attemt on doing so is foollows:

myDict = myDict.Select(x => x.Value.OrderBy(v => v.Key.Remove(0, v.Key.IndexOf('_')))).ToDictionary();


How could I do this?

Answer

ToDictionary requires two parameters - one for the key selector and one for the value selector, so you could do something like:

myDict = myDict.ToDictionary(
            kvp => kvp.Key,
            kvp => ICollection<KeyValuePair<s‌​tring, int>>
                        kvp.Value.OrderBy(v => v.Key.Remove(0, v.Key.IndexOf('_')))
                            .ToList()
            );
Comments