C#对Dictionary的Value排序功能实现

C#2.0 (VS2005)实现方法:

 

                Dictionary<string, string> dic = new Dictionary<string, string>();

                dic.Add("2", "c Item");

                dic.Add("6", "f Item");

                dic.Add("1", "a Item");

                dic.Add("7", "g Item");

                dic.Add("3", "b Item");

                dic.Add("5", "e Item");

                dic.Add("4", "d Item");

 

                List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(dic);

 

                myList.Sort(delegate(KeyValuePair<string, string> s1, KeyValuePair<string, string> s2)

                    {

                        return s1.Value.CompareTo(s2.Value);

                    });

 

                dic.Clear();

 

                foreach (KeyValuePair<string, string> pair in myList)

                {

                    dic.Add(pair.Key, pair.Value);

                }

 

                foreach (string key in dic.Keys)

                {

                    Response.Write(dic[key] + "<br />");

                }

 

 

 

C#3.0 Lambda表达式 VS2008)的实现方法:

 

 

 

 

            Dictionary<string, string> dic = new Dictionary<string, string>();

            dic.Add("2", "c Item");

            dic.Add("6", "f Item");

            dic.Add("1", "a Item");

            dic.Add("7", "g Item");

            dic.Add("3", "b Item");

            dic.Add("5", "e Item");

            dic.Add("4", "d Item");

 

            var list = dic.OrderBy(s => s.Value);

 

            foreach (var s in list)

            {

                Response.Write(s.Value + "<br />");

            }

 

 

 

C#3.0 Linq VS2008)的实现方法:

 

            Dictionary<string, string> dic = new Dictionary<string, string>();

            dic.Add("2", "c Item");

            dic.Add("6", "f Item");

            dic.Add("1", "a Item");

            dic.Add("7", "g Item");

            dic.Add("3", "b Item");

            dic.Add("5", "e Item");

            dic.Add("4", "d Item");

 

            var dicSort = from d in dic

                          orderby d.Value

                          ascending

                          select d;

 

            foreach (string key in dic.Keys)

            {

                Response.Write(dic[key] + "<br />");

            }

你可能感兴趣的:(String,list,C#,lambda,LINQ,Dictionary)