码迷,mamicode.com
首页 > 编程语言 > 详细

SortedDictionary<TKey,TValue>正序与反序排序

时间:2015-12-14 21:11:02      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

SortedDictionary<TKey,TValue>能对字典排序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SortDictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            TestDictionarySort();
            TestDictionarySort2();
            Console.Read();
        }
        private static void TestDictionarySort()
        {
            SortedDictionary<string, string> sd = new SortedDictionary<string, string>();
            sd.Add("321", "fdsgsags");
            sd.Add("acb", "test test");
            sd.Add("1123", "lslgsgl");
            sd.Add("2bcd13", "value");

            foreach (KeyValuePair<string, string> item in sd)
            {
                Console.Write("键名:" + item.Key + " 键值:" + item.Value+"\r\n");
            }

        }

        private static void TestDictionarySort2()
        {
            SortedDictionary<string, string> sd = new SortedDictionary<string, string>();
            sd.Add("321", "fdsgsags");
            sd.Add("acb", "test test");
            sd.Add("1123", "lslgsgl");
            sd.Add("2bcd13", "value");

            Console.Write("\r\n正序排序数据:\r\n");
            foreach (KeyValuePair<string, string> item in sd)
            {
                Console.Write("键名:" + item.Key + " 键值:" + item.Value + "\r\n");
            }

            //重新封装到Dictionary里(PS:因为排序后我们将不在使用排序了,所以就使用Dictionary)
            Dictionary<string, string> dc = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> item in sd.Reverse())
            {
                dc.Add(item.Key, item.Value);
            }
            sd = null;
            //再看其输出结果:
            Console.Write("\r\n反序排序数据:\r\n");
            foreach (KeyValuePair<string, string> item in dc)
            {
                Console.Write("键名:" + item.Key + " 键值:" + item.Value + "\r\n");
            } 
        }

    }
}

结果:

技术分享

 

SortedDictionary<TKey,TValue>正序与反序排序

标签:

原文地址:http://www.cnblogs.com/shy1766IT/p/5046389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!