Sort SortedDictionary by to the value

55 Views Asked by At

I have sorted dictionary like below:

var map = new SortedDictionary<string, List<Account>>();

I need to sort it by value size (so List>.Count). How do I do that?

I tried as suggested by this forum:

List<KeyValuePair<string, List<Account>>> myList = map.ToList();
            myList.Sort(delegate (KeyValuePair<string, List<Account>> pair1,
                                    KeyValuePair<string, List<Account>> pair2)
            {
                return pair1.Value.Count.CompareTo(pair2.Value.Count);
            }
            );

but that didn't work

2

There are 2 best solutions below

0
Guru Stron On

While shown method should work (and it did for me), I would suggest to use the LINQ here:

List<KeyValuePair<string, List<Account>>> myList = map
    .OrderBy(kvp => kvp.Value.Count) // OrderByDescending if higher counts needed first
    .ToList();
0
Harald Coppoolse On

I need to sort it by value size (so List>.Count). How do I do that?

What is "it"? Do you want as a result a Dictionary, or a sequence of `List', ordered by descending number of elements in the List? Next time consider to be more specific about your requirements.

If you want a sequence of List<Account>, the first List in the sequence being the largest, do the following:

SortedDictionary<string, List<Account>> map = ...
IEnumerable<List<Account>> accountListsInMap = map
    .Select(keyValuePair => keyValuePair.Value);
IEnumerable<List<Account>> listsOrderedByDescendingSize = accountListsInMap
    .OrderBy(accountList => accountList.Count);

Of course you can do this in one big LINQ statement. Nut sure though whether this will improve efficiency. However it will deteriorate readability.