简体   繁体   English

我们如何对字典进行排序<list<int> , 列表<int> &gt; 基于两个字段的值</int></list<int>

[英]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]. list1、list2 和 list3 的最小值和最大值分别为 [2,98]、[3,78] 和 [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.据我了解,您实际上只需要按 Value 对字典进行排序,这实际上只是 Key 中的 Min 和 Max 元素。 And the order should go by the Max elements and then by the Min elements if the Max elements are equal.如果 Max 元素相等,则顺序应按 Max 元素,然后按 Min 元素 go 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 :您可以使用OrderBy方法对字典进行排序,并传入一个自定义IComparer

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

MinMaxComparer here looks like:这里的MinMaxComparer看起来像:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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