2

我试图在Dictionary<int, int>不使用 LINQ 的情况下按其值订购 C#,OrderBy因为 iPhone 不支持它。

我似乎无法弄清楚,所以你的帮助将不胜感激!

4

2 回答 2

4

There are many possible ways of doing this. All of the following assume myDictionary is the original dictionary to be sorted.

① Create a list and then sort the list

var myList = myDictionary.ToList();
myList.Sort((a, b) => a.Value.CompareTo(b.Value));

② Create an array and then sort the array

var myArray = myDictionary.ToArray();
Array.Sort(myArray, (a, b) => a.Value.CompareTo(b.Value));

③ Create a new SortedDictionary that has keys and values swapped

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;

④ Create a new SortedDictionary and use lists for values

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);
}
于 2014-04-29T08:40:41.983 回答
0

我们可以生成一个ListofKeyValuePair然后使用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 上得到支持

于 2014-04-29T08:33:11.937 回答