[英]sort a dictionary's keys based on its values; values represent arrays and sorting order varies - ascending/descending; c#
我想對對象列表進行排序。 該結構是一個Dictionary<object, double[]>
,如下所示:
Dictionary<int, double[]> dict = new Dictionary<int, double[]>{
{object1, new double[]{0.02, 0.10, 0.30, 0.5}},
{object4, new double[]{0.02, 0.10, 0.30, 0.2}},
{object3, new double[]{0.02, 0.10, 0.30, 0.3}},
{object2, new double[]{0.02, 0.10, 0.50, 0.4}}
};
數組應根據索引以不同的順序排列。 即第 1、2 和 4 指數升序,第 3 指數降序。 所以最終,我應該得到:
object2, 0.02, 0.1, 0.5, 0.4
object4, 0.02, 0.1, 0.3, 0.2
object3, 0.02, 0.1, 0.3, 0.3
object1, 0.02, 0.1, 0.3, 0.5
我使用此處發布的代碼作為起點。 我應該做什么樣的調整? 當然,我知道該方法將不再是通用的(與數組長度無關)。 我正在考慮創建一個與double[]
大小相同的bool[]
,其中True
代表升序排序, False
代表降序,但 Compare 方法嚴格獲取 2 個參數。 任何幫助將非常感激。 謝謝!
您可以使用Linq庫。 在字典上調用OrderBy
。
var x = dict.OrderBy(o => o.Value[0]).ThenBy(o => o.Value[1]).ThenBy(o => -o.Value[2]).ThenBy(o => o.Value[3]);
完整代碼:
using System.Linq;
...........
public static void Main()
{
var object1 = 1;
var object2 = 2;
var object3 = 3;
var object4 = 4;
Dictionary<int, double[]> dict = new Dictionary<int, double[]>{
{object1, new double[]{0.02, 0.10, 0.30, 0.5}},
{object4, new double[]{0.02, 0.10, 0.30, 0.2}},
{object3, new double[]{0.02, 0.10, 0.30, 0.3}},
{object2, new double[]{0.02, 0.10, 0.50, 0.4}}
};
var x = dict.OrderBy(o => o.Value[0]).ThenBy(o => o.Value[1]).ThenBy(o => -o.Value[2]).ThenBy(o => o.Value[3]);
// write ordered values
foreach (var d in x)
{
Console.Write(d.Key + ", [");
foreach (var v in d.Value)
Console.Write(v + ", ");
Console.WriteLine("]");
}
}
輸出
2, [0.02, 0.1, 0.5, 0.4, ]
4, [0.02, 0.1, 0.3, 0.2, ]
3, [0.02, 0.1, 0.3, 0.3, ]
1, [0.02, 0.1, 0.3, 0.5, ]
如果我猜對了,請嘗試使用此比較器:
public class SequenceComparer : IComparer<IList<double>>
{
public SequenceComparer(bool[] markers)
{
Markers = markers;
}
public bool[] Markers { get; }
public int Compare(IList<double> x, IList<double> y)
{
//check for null
if (x == null || y == null || Markers == null)
{
throw new Exception("Null arrays are not valid");
}
//check identical count
if (x.Count != y.Count || x.Count != Markers.Length)
{
throw new Exception("Invalid count");
}
for (var i = 0; i < x.Count; i++)
{
if (x[i].Equals(y[i]))
{
continue;
}
var comparisonResult = x[i] > y[i] ? 1 : -1;
//if marker is false, invert comparisonResult
return Markers[i] ? comparisonResult : comparisonResult * -1;
}
//Your arrays are identical, just skip
return 1;
}
}
您可以使用任何長度的數組並使用bool[]
標志調節排序方向
使用示例:
var query = dict.OrderBy(pair => pair.Value, new SequenceComparer(new []{true, true, false, true}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.