C# Dictionary的遍历和排序
作者:网络转载 发布时间:[ 2016/6/13 10:17:06 ] 推荐标签:测试开发技术 .NET
c#遍历的两种方式 for和foreach
for: 需要指定首位数据、末尾数据、数据长度; for遍历语句中可以改变数据的值; 遍历规则可以自定义,灵活性较高
foreach: 需要实现ienumerator接口; 在遍历中不可以改变数据的值; 遍历规则只能是'++' ; 但查询效率较高
Dictionary遍历方式:
Dictionary<string, int> list = new Dictionary<string, int>();
list.Add("d", 1);
//3.0以上版本
foreach (var item in list)
{
Console.WriteLine(item.Key + item.Value);
}
//KeyValuePair<T,K>
foreach (KeyValuePair<string, int> kv in list)
{
Console.WriteLine(kv.Key + kv.Value);
}
//通过键的集合取
foreach (string key in list.Keys)
{
Console.WriteLine(key + list[key]);
}
//直接取值
foreach (int val in list.Values)
{
Console.WriteLine(val);
}
//非要采用for的方法也可
List<string> test = new List<string>(list.Keys);
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(test[i] + list[test[i]]);
}
List排序:
Hashtable ht=new Hashtable();
ht.Add("E","e");
ht.Add("A","a");
ht.Add("C","c");
ht.Add("B","b");
ArrayList lst=new ArrayList(ht.Keys);
lst.Sort();
foreach(string key in lst)
{
listBox1.Items.Add("key:" + key + " vlaue:"+ht[key]);
}
Dictionary排序
排序思路:
1>用一个List保存Dictionary的数据
2>对新的List进行排序
3>从List获取排序好的值,重新添加进Dictionary
protected Dictionary<string, int> SortDictionary_Desc(Dictionary<string, int> dic)
{
List<KeyValuePair<string, int>> myList = new List<KeyValuePair<string, int>>(dic);
myList.Sort(delegate(KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)
{
return s2.Value.CompareTo(s1.Value);
});
dic.Clear();
foreach (KeyValuePair<string, int> pair in myList)
{
dic.Add(pair.Key, pair.Value);
}
return dic;
}
protected Dictionary<string, int> SortDictionary_Asc(Dictionary<string, int> dic)
{
List<KeyValuePair<string, int>> myList = new List<KeyValuePair<string, int>>(dic);
myList.Sort(delegate(KeyValuePair<string, int> s1, KeyValuePair<string, int> s2)
{
return s1.Value.CompareTo(s2.Value);
});
dic.Clear();
foreach (KeyValuePair<string, int> pair in myList)
{
dic.Add(pair.Key, pair.Value);
}
return dic;
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11