您的位置:首页 > 产品设计 > UI/UE

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

2015-12-14 19:56 501 查看
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");
}
}

}
}


结果:



通过字典key得到value

var keywordDic = new Dictionary<int, string>()
{
{0,"搜索关键字"},
{1,"分类id"},
{2,"品牌id"}
};
var keywordCode = keywordDic[(int)item.KeyWordType];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: