Record the improper use of SortedDictionary once, sorteddictionary
At first, I wanted to use SortedDictionary to play the ranking in the game. The Code is as follows:
using UnityEngine;using System;using System.Collections;using System.Collections.Generic;public class CustomComparer<T> : IComparer<T>{ Func<T, T, int> mComparerFunc; public CustomComparer(Func<T, T, int> comparer) { this.mComparerFunc = comparer; } public int Compare(T x, T y) { return mComparerFunc(x, y); }}public class SortedDictTest : MonoBehaviour{ SortedDictionary<string, int> mLeaderboard; void Start() { mLeaderboard = new SortedDictionary<string, int>(new CustomComparer<string>((x, y) => mLeaderboard[x].CompareTo(mLeaderboard[y]))); mLeaderboard.Add("Jhon", 10); mLeaderboard.Add("Dark", 40); mLeaderboard.Add("Ellie", 20); foreach (var item in mLeaderboard) { Debug.Log("Name: " + item.Key + " Score: " + item.Value); } }}
The result is an endless unity loop.
When you get a value in the dictionary, it calls the comparator. The dictionary is called in the comparator, causing an endless loop.
There is also a problem with this usage. The sorting dictionary sorts keys, and there is a mechanism similar to binary search in the operation.
During ranking, You need to match by name and automatically sort by score. In this case, there are two sorting mechanisms. The internal order of the dictionary is chaotic, and the query speed is slower.
There are also some solutions, which can be solved using dual dictionary:
public class SortedDictTest : MonoBehaviour{ Dictionary<string, int> mScoreDict; SortedDictionary<string, int> mLeaderboard; void Start() { mScoreDict = new Dictionary<string, int>(); mLeaderboard = new SortedDictionary<string, int>(new CustomComparer<string>((x, y) => mScoreDict[x].CompareTo(mScoreDict[y]))); mScoreDict.Add("Jhon", 10); mScoreDict.Add("Dark", 40); mScoreDict.Add("Ellie", 20); mLeaderboard.Add("Jhon", 10); mLeaderboard.Add("Dark", 40); mLeaderboard.Add("Ellie", 20); foreach (var item in mLeaderboard) { Debug.Log("Name: " + item.Key + " Score: " + item.Value); } }}
It depends on the amount of data to weigh, and it is hard to directly use List sorting.