none
c#字典 Dictionary排序问题 RRS feed

  • 问题

  • 现有字典
    Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
    dic.Add("bca", new List<string>(){"xkyz"} );
    dic.Add("c", new List<string>(){"xdz"} );
    dic.Add("absdc", new List<string>(){"xyz"} );
    dic.Add("dxzcu", new List<string>(){"fyz"} );
    排序依据字典健的长度来排序,越长的越在前面,列表的值不变只改变顺序
    Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
    dic.Add("dxzcu", new List<string>(){"fyz"} );
    dic.Add("absdc", new List<string>(){"xyz"} );
    dic.Add("bca", new List<string>(){"xkyz"} );
    dic.Add("c", new List<string>(){"xdz"} );

    2012年4月19日 3:44

答案

  • 默认情况下Dictionary输出是你Add时候的顺序,要想改变顺序,请先对Dictionary排序,然后重新添加:

    namespace MyTest
    {
        public class CompareClass : IComparer<KeyValuePair<string,List<string>>>
        {
            public int Compare(KeyValuePair<string, List<string>> x, KeyValuePair<string, List<string>> y)
            {
                //Key一样比较字符串大小
                if (x.Key.Length == y.Key.Length)
                {
                    return x.Key.CompareTo(y.Key);
                }
                return x.Key.Length - y.Key.Length;
            }
        }
        public class MonthActualapp
        {
            public static void Main(string[] args)
            {
                Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
                dic.Add("bca", new List<string>() { "xkyz" });
                dic.Add("c", new List<string>() { "xdz" });
                dic.Add("absdc", new List<string>() { "xyz" });
                dic.Add("dxzcu", new List<string>() { "fyz" });
    
               var result= dic.OrderByDescending((o) => o,new CompareClass()).Select(p => p).ToArray();
               dic.Clear();
               
               foreach (var item in result)
               {
                   dic.Add(item.Key, item.Value);
               }
    
                //输出
               foreach (var item in dic)
               {
                   Console.WriteLine(item.Key+"<===>"+item.Value[0]);
               }
            }
        }
    }

       QQ我:讨论(Talk)
    下载MSDN桌面工具(Vista,Win7)
    我的博客园
    慈善点击,点击此处


    2012年4月19日 4:50
    版主