[英]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.