遇到三方接口计算签名等操作需要对字符串排序:
var dictionary = new Dictionary<string, string> {
{"a", "a"},
{"A", "A"},
{"Z", "A"},
{"b", "b"}
};
var sortedDictionary = dictionary.OrderBy(d => d.Key, StringComparer.Ordinal);
var signSource = string.Join("&", sortedDictionary.Select(kv => $"{kv.Key}={kv.Value}"));
这里我们期望的顺序通常是 A-Z-a-b
,因为按照字典顺序,大写字母都是小于小写字母的,
排序的代码中必须添加StringComparer.Ordinal
,否则顺序会是 a-A-b-Z
全部评论