大家好,请教一个问题,我定义了一个Dictionary,代码如下       Dictionary<string, string> test = new Dictionary<string, string>();
            test.Add("a", "w");
            test.Add("z", "w");
            test.Add("s", "w");
我希望根据主键对 test中的元素进行排序,结果如下test[0]: ("a","w")test[1]: ("s","w")test[2]: ("z","w")
请问如何排序?请问是不是如果Dictionary中的元素是已经排序好的,用test["s"]查找更快?多谢大家指教

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.Linq;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Dictionary<string, string> test = new Dictionary<string, string>();
                test.Add("a", "w");
                test.Add("z", "w");
                test.Add("s", "w");            foreach (KeyValuePair<string, string> t in test)
                {
                    Console.WriteLine("Key:"+t.Key + "  Value:" +t.Value);
                }            var temp = test.OrderBy(x => x.Key);            Console.WriteLine();            foreach (KeyValuePair<string, string> t in temp)
                {
                    Console.WriteLine("Key:" + t.Key + "  Value:" + t.Value);
                }            Console.Read();
            }
        }
    }
      

  2.   


    static void Main(string[] args)
            {
                Dictionary<string, string> test = new Dictionary<string, string>();
                test.Add("a", "w");
                test.Add("z", "w");
                test.Add("s", "w");            var q = from c in test
                        orderby c.Key ascending
                        select c;            foreach (KeyValuePair<string, string> item in q)
                {
                    Console.WriteLine("key={0} value={1}", item.Key, item.Value);
                }
                Console.Read();
            }