我试图在Dictionary<int, int>
不使用 LINQ 的情况下按其值订购 C#,OrderBy
因为 iPhone 不支持它。
我似乎无法弄清楚,所以你的帮助将不胜感激!
我试图在Dictionary<int, int>
不使用 LINQ 的情况下按其值订购 C#,OrderBy
因为 iPhone 不支持它。
我似乎无法弄清楚,所以你的帮助将不胜感激!
There are many possible ways of doing this. All of the following assume myDictionary
is the original dictionary to be sorted.
var myList = myDictionary.ToList();
myList.Sort((a, b) => a.Value.CompareTo(b.Value));
var myArray = myDictionary.ToArray();
Array.Sort(myArray, (a, b) => a.Value.CompareTo(b.Value));
This solution is appropriate only if you know that every value occurs only once.
var mySortedDict = new SortedDictionary<int, int>();
foreach (var kvp in myDictionary)
mySortedDict[kvp.Value] = kvp.Key;
This solution is appropriate only if values can occur more than once.
var mySortedDict = new SortedDictionary<int, List<int>>();
foreach (var kvp in myDictionary)
{
if (!mySortedDict.ContainsKey(kvp.Value))
mySortedDict[kvp.Value] = new List<int>();
mySortedDict[kvp.Value].Add(kvp.Key);
}
我们可以生成一个List
ofKeyValuePair
然后使用Sort
,
Dictionary<int, int> myList = new Dictionary<int, int>();
List<KeyValuePair<int, int>> mySortedList = myList.ToList();
mySortedList.Sort(( firstValue, nextValue) =>
{
return firstValue.Value.CompareTo(nextValue.Value);
}
);
Dictionary<int, int> mySortedDict = mySortedList.ToDictionary(keyItem => keyItem.Key, keyItem => keyItem.Value);
我认为Sort
将在 iPhone 上得到支持