目录
1 测试用例
如下表格,我们要按照各个区域面积进行字典排序
政区 | 面积 |
闵行区 | 6732.115 |
浦东新区 | 2553.8811 |
青浦区 | 5623.1175 |
嘉定区 | 15438.22 |
2 字典按Value排序
using System;
using System.Collections.Generic;
public class Test
{
public static Dictionary<string, double> sortDictByValue(Dictionary<string, double> dic)
{
List<KeyValuePair<string, double>> myList = new List<KeyValuePair<string, double>>(dic);
myList.Sort(delegate(KeyValuePair<string, double> s1, KeyValuePair<string, double> s2)
{
return s1.Value.CompareTo(s2.Value);
});
dic.Clear();
foreach (KeyValuePair<string, double> pair in myList)
{
dic.Add(pair.Key, pair.Value);
}
return dic;
}
public static void ouputResult(Dictionary<string, double> dic)
{
foreach(KeyValuePair<string, double> pair in dic)
{
Console.WriteLine(pair.Key + "\t" + pair.Value);
}
}
public static void Main()
{
Dictionary<string, double> dic = new Dictionary<string, double>();
dic.Add("闵行区", 6732.115);
dic.Add("浦东新区", 2553.8811);
dic.Add("青浦区", 5623.1175);
dic.Add("嘉定区", 15438.22);
dic = sortDictByValue(dic);
ouputResult(dic);
}
}
3 测试结果
将上述代码复制到在线编译器中,即可测试。c#在线编译器,C#在线代码执行,在线测试代码 (dooccn.com)