c# Dictionary的遍历和排序

 

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;
        }

 

转载于:https://www.cnblogs.com/eye-like/p/4155943.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值