简体   繁体   中英

How can we Sort a dictionary<List<int>, List<int>> on the basis of two fields from value

As a part of key I am storing a List and in Value I want to store max and min values of that list. Later there will be many lists like that. I need to sort for the dictionary having minimum possible maximum element value and minimum possible minimum element value

Something like

var map= Dictionary<List<int>, List<int>>()

Consider few list like

List1=[21,65,98,9,2] List2=[3,46,78,09,17] List3=[3,6,0,98] 

respective min and max for list1, list2 and list3 are [2,98], [3,78] and [0,98]. These values will be stored in the dictionary value(with associated list as key).

I want to sort in the dictionary, keeping a track of both min and max value. Something like:

map= {[3,6,0,98] ,[0,98]} , {[21,65,98,9,2],[2,98]}, {[3,46,78,09,17], [3,78]}

From what I understand, you really just need to order the dictionary by the Value, which is really just the Min and Max elements from the Key. And the order should go by the Max elements and then by the Min elements if the Max elements are equal. So, given this data:

var dictionary = new Dictionary<List<int>, List<int>>
{
    { new List<int> {3,6,0,98 }, new List<int> {0,98 } },
    { new List<int> {21,65,98,9,2 },new List<int> {2,98 } },
    { new List<int> {3,46,78,09,17 }, new List<int> {3,78 } }
};

You can sort the dictionary using the OrderBy method, passing in a custom IComparer :

var sorted = dictionary.OrderBy(x => x.Value, new MinMaxCompararer());

MinMaxComparer here looks like:

class MinMaxCompararer : IComparer<List<int>>
{
    public int Compare([AllowNull] List<int> x, [AllowNull] List<int> y)
    {
        int maxCompare = x[1].CompareTo(y[1]);
        return maxCompare == 0
            ? x[0].CompareTo(y[0])
            : maxCompare;
    }
}

With this, iterating over the elements shows them sorted as you'd expect:

foreach (KeyValuePair<List<int>, List<int>> item in sorted)
{
    Console.WriteLine($"Key: [{string.Join(",", item.Key)}]; Value: [{string.Join(",", item.Value)}]");
}
Key: [3,46,78,9,17]; Value: [3,78]
Key: [3,6,0,98]; Value: [0,98]
Key: [21,65,98,9,2]; Value: [2,98]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM