问题:
你想要对一个Dictionary中包含的键和/或值排序,以便把整个Dictionary显示给用户,并以升序或降序方式对它进行排序。
解决方案:
通过LINQ查询以及Dictionary<T,U>对象的Keys和Values属性,获得其键和值对象的有序ICollection.下面所示的代码显示以升序或降序排序的Dictionary<T,U>的键和值。
public static void TestSortKeyValues()
{
// Define a Dictionary<T,U> object
Dictionary<string, string> hash = new Dictionary<string, string>()
{
["2"] = "two",
["1"] = "one",
["5"] = "five",
["4"] = "four",
["3"] = "three"
};
var x = from k in hash.Keys orderby k ascending select k;
foreach (string s in x)
Console.WriteLine($"Key: {s} Value: {hash[s]}");
Console.WriteLine