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 = ;
while (index < iLeftLength && index < iRightLength)
{
if (sLeft[index] < sRight[index])
return -;
else if (sLeft[index] > sRight[index])
return ;
else
index++;
}
return iLeftLength - iRightLength; }
} string[] arr = { "E0o2-at6NcC2OsJiQTlwlCYXETNlXymc-tIaxXdRNahmhLtvORQGZfIvXWmiTberoB4ARrwHR-XxB47vfIKY_Q",
"",
"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