日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

c# Dictionary的遍历和排序

發(fā)布時(shí)間:2025/7/14 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c# Dictionary的遍历和排序 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

c# Dictionary的遍歷和排序

?

c#遍歷的兩種方式 for和foreach

  for: 需要指定首位數(shù)據(jù)、末尾數(shù)據(jù)、數(shù)據(jù)長(zhǎng)度; for遍歷語(yǔ)句中可以改變數(shù)據(jù)的值; 遍歷規(guī)則可以自定義,靈活性較高

  foreach: 需要實(shí)現(xiàn)ienumerator接口; 在遍歷中不可以改變數(shù)據(jù)的值; 遍歷規(guī)則只能是'++' ; 但查詢效率較高

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); }//通過(guò)鍵的集合取 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>用一個(gè)List保存Dictionary的數(shù)據(jù)

  2>對(duì)新的List進(jìn)行排序

  3>從List獲取排序好的值,重新添加進(jìn)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;}

轉(zhuǎn)載于:https://www.cnblogs.com/wangluochong/p/5576573.html

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。