Array.Sort可以實現便捷的字典排序,但如果完全相信他,那麼就容易產生些異常!太順利了,往往是前面有坑等你。
比如:微信介面,好多地方需要簽名認證,簽名的時候需要用的字典排序,如果只用Array.Sort()會出現簽名異常的情況,而且是偶爾出現。
問題就在於他的排序預設沒有區分大小寫,這跟微信的簽名將不匹配,所以還是需要自己實現比較的方法
public class DictionarySort : System.Collections.IComparer { public int Compare(object oLeft, object oRight) { string sLeft = oLeft as string; string sRight = oRight as string; int iLeftLength = sLeft.Length; int iRightLength = sRight.Length; int index = 0; while (index < iLeftLength && index < iRightLength) { if (sLeft[index] < sRight[index]) return -1; else if (sLeft[index] > sRight[index]) return 1; else index++; } return iLeftLength - iRightLength; } } string[] arr = { "E0o2-at6NcC2OsJiQTlwlCYXETNlXymc-tIaxXdRNahmhLtvORQGZfIvXWmiTberoB4ARrwHR-XxB47vfIKY_Q", "1449221063", "p8hR6s3Eljz2TLLJab7rmJaOXHvc", "a9233845d1c74e8194e6979a4210c804" }; Array.Sort(arr); string tmpStr = string.Join("", arr); this.textBox1.Text = tmpStr; //1449221063a9233845d1c74e8194e6979a4210c804E0o2-at6NcC2OsJiQTlwlCYXETNlXymc-tIaxXdRNahmhLtvORQGZfIvXWmiTberoB4ARrwHR-XxB47vfIKY_Qp8hR6s3Eljz2TLLJab7rmJaOXHvc Array.Sort(arr, new DictionarySort()); this.textBox2.Text = string.Join("", arr); //1449221063E0o2-at6NcC2OsJiQTlwlCYXETNlXymc-tIaxXdRNahmhLtvORQGZfIvXWmiTberoB4ARrwHR-XxB47vfIKY_Qa9233845d1c74e8194e6979a4210c804p8hR6s3Eljz2TLLJab7rmJaOXHvc