[英]Sorting Dictionary <string, List<int>> based on value
I have a dictionary of string as key and an ordered List of Integers List as Values; 我有一个字符串字典作为键,有序的整数列表作为值。 Is it possible to have it ordered based on order of values in c#? 是否可以根据c#中的值顺序对其进行排序?
For example: myDict : 例如:myDict:
{
"hp",<10,14,23>
"dell", <6,8,9,10>
"asus", <6,9,18>
"mac", <7,98>
}
Sorted as: 排序为:
{
"dell", <6,8,9,10>
"asus", <6,9,18>
"mac", <7,98>
"hp",<10,14,23>
}
Here is what I have tried: 这是我尝试过的:
//this creates a dictionary with requirements stated above for testing
Dictionary<string, List<int>> myDict = new Dictionary<string, List<int>
>();
var numbers = "8,13,16,21,24,25,31,33,36,63,66,70,76,82,94".Split(',').Select(Int32.Parse).ToList();
myDict .Add("asus", numbers);
numbers = "6,84,90,99".Split(',').Select(Int32.Parse).ToList();
myDict .Add("dell", numbers);
numbers = "10,11,20,21,23,26,28,29,31,38,39,40,50,52,61,65,66,70,75,94".Split(',').Select(Int32.Parse).ToList();
myDict.Add("hp", numbers);
numbers = "4,17,42,56,62,79,80".Split(',').Select(Int32.Parse).ToList();
myDict .Add("mac",numbers );
The part that is suppose to do the sorting: 假定要进行排序的部分:
var orderedDictionary = myDict.OrderByDescending(pairs => pairs.Value);
The above gives an error of "At least one object must implement IComparable." 上面的错误为“至少一个对象必须实现IComparable”。 I have also tried converting the list to string and doing the following: 我也尝试过将列表转换为字符串并执行以下操作:
var sortedDict = from entry in myDict
orderby entry.Value
ascending
select entry;
The above worked however it treats numbers as strings; 上面的工作但是将数字视为字符串; hence 10,85 would appear before 8,6 I am guessing it is because "," ASCII representation is higher than numbers. 因此10,85将在8,6之前出现,我猜这是因为“,” ASCII表示高于数字。
How do I come to sort a dictionary with sorted list of integers in c#? 如何在C#中使用整数列表对字典进行排序? or the only way to do a manual sorting by checking each cell over the other cells? 还是通过检查每个单元格而不是其他单元格来进行手动排序的唯一方法?
You should implement IComparer<T>
for your List<int>
: 您应该为List<int>
实现IComparer<T>
List<int>
:
public MyListComparer : IComparer<List<int>>
{
public int Compare(List<int> x, List<int> y)
{
var minLength = x.Count < y.Count ? x.Count : y.Count;
for (var i = 0 ;i < minLength; i++)
{
if (x[i] > y[i])
{
return 1;
}
if (x[i] < y[i])
{
return -1;
}
}
if (x.Count > y.Count)
{
return 1;
}
if (y.Count > x.Count)
{
return -1;
}
return 0;
}
}
And use it with this overload of LINQ OrderBy : 并与LINQ OrderBy的此重载一起使用:
var orderedDictionary = myDict.OrderBy(pairs => pairs.Value, new MyListComparer());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.