C#对Dictionary的按Value排序

本文详细介绍了如何利用C#3.0的Lambda表达式和Linq来对字典集合进行排序操作,并通过实例展示了具体实现方法。
 

使用List对其进行排序

using System;
using System.Collections.Generic;
using System.Text;


namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

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

            dic.Add("Arraymin", "c:\\demo\\min.xsl");

            dic.Add("Arraymax", "c:\\demo\\max.xsl");


            dic.Add("Arrayr", "c:\\demo\\r.xsl");


            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)
            {

                Console.WriteLine(dic[key]);

            }

            Console.ReadKey();
        }
      
    }
}

 

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

 

 

 

 

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

           dic.Add("Arraymin", "c:\\demo\\min.xsl");

            dic.Add("Arraymax", "c:\\demo\\max.xsl");


            dic.Add("Arrayr", "c:\\demo\\r.xsl");

 

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

 

            foreach (var s in list)

            {

                Console.WriteLine(dic[key]);            }

 

 

 

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

 

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

            dic.Add("Arraymin", "c:\\demo\\min.xsl");

            dic.Add("Arraymax", "c:\\demo\\max.xsl");


            dic.Add("Arrayr", "c:\\demo\\r.xsl");

 

            var dicSort = from d in dic

                          orderby d.Value

                          ascending

                          select d;

 

            foreach (string key in dic.Keys)

            {

              Console.WriteLine(dic[key]);

            }


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值