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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM