【问题标题】:How can we Sort a dictionary<List<int>, List<int>> on the basis of two fields from value我们如何根据 value 中的两个字段对字典<List<int>、List<int>> 进行排序
【发布时间】:2021-07-06 21:28:23
【问题描述】:

作为键的一部分,我正在存储一个列表,并且在值中我想存储该列表的最大值和最小值。以后会有很多这样的列表。我需要对具有最小可能最大元素值和最小可能最小元素值的字典进行排序

类似

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

考虑一些类似的列表

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

list1、list2 和 list3 的最小值和最大值分别为 [2,98]、[3,78] 和 [0,98]。这些值将存储在字典值中(以关联列表为键)。

我想在字典中排序,同时记录最小值和最大值。 比如:

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

【问题讨论】:

  • c#中有一个数据类型叫SortedDictionary。请参阅docs.microsoft.com/en-us/dotnet/api/…。这可能会有所帮助。
  • 如果有两项,一项为[1,5],一项为[2,6],排序的时候哪个在前?
  • 您不能将集合作为键。此外,密钥必须是唯一的。您可以使用 ValueTuple 将最小值和最大值存储为键,但前提是这对值是唯一的。
  • 一些代码可能会有所帮助:我们无法看到您想要如何执行此操作的上下文
  • @OlivierJacot-Descombes 我明白,但你说你不能有一个集合作为键,你可以

标签: c# sorting dictionary max min


【解决方案1】:

据我了解,您实际上只需要按 Value 对字典进行排序,这实际上只是 Key 中的 Min 和 Max 元素。如果 Max 元素相等,则顺序应按 Max 元素,然后按 Min 元素。所以,鉴于这些数据:

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

您可以使用OrderBy 方法对字典进行排序,传入自定义的IComparer

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

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

这样,遍历元素会显示它们按您期望的方式排序:

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-11
    • 2010-10-17
    • 2016-06-26
    • 2015-01-14
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2016-08-19
    相关资源
    最近更新 更多