日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

c# Dictionary的遍历和排序

發布時間:2025/7/14 C# 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c# Dictionary的遍历和排序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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/wangluochong/p/5576573.html

總結

以上是生活随笔為你收集整理的c# Dictionary的遍历和排序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。