[英]How can we Sort a dictionary<List<int>, List<int>> on the basis of two fields from value
作为键的一部分,我正在存储一个列表,并且在值中我想存储该列表的最大值和最小值。 以后会有很多这样的列表。 我需要对具有最小可能最大元素值和最小可能最小元素值的字典进行排序
就像是
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]}
据我了解,您实际上只需要按 Value 对字典进行排序,这实际上只是 Key 中的 Min 和 Max 元素。 如果 Max 元素相等,则顺序应按 Max 元素,然后按 Min 元素 go 因此,鉴于此数据:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.