本文主要介绍.NET Core(C#)中,根据字典Dictionary的key值进行排序的方法,以及相关的示例代码。
1、先将key排序在添加排序后的key和value
using System;
using System.Collections.Generic;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
Dictionary<string,Point> r=new Dictionary<string,Point>();
r.Add("c3",new Point(0,1));
r.Add("c1",new Point(1,2));
r.Add("t3",new Point(2,3));
r.Add("c4",new Point(3,4));
r.Add("c2",new Point(4,5));
r.Add("t1",new Point(5,6));
r.Add("t2",new Point(6,7));
List<string> zlk=new List<string>(r.Keys);
zlk.Sort();
List<Point> zlv=new List<Point>();
// Readd with the order.
foreach(var item in zlk) {
zlv.Add(r[item]);
}
r.Clear();
for(int i=0;i<zlk.Count;i++) {
r[zlk[i]]=zlv[i];
}
foreach(var item in r.Keys) {
Console.WriteLine(item+" "+r[item].X+" "+r[item].Y);
}
Console.ReadKey(true);
}
}
}
2、通过Linq的OrderBy()排序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dictionary<int, string> test = new Dictionary<int, string> { };
test.Add(0,"C#");
test.Add(3, "Java");
test.Add(1, "Python");
test.Add(9, "cjavapy");
Dictionary<int, string> dic1Asc = test.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
Console.WriteLine("小到大排序");
foreach(KeyValuePair<int,string> k in dic1Asc){
Console.WriteLine("key:" +k.Key +" value:" + k.Value);
}
Console.WriteLine("大到小排序");
Dictionary<int, string> dic1desc = test.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
foreach (KeyValuePair<int, string> k in dic1desc)
{
Console.WriteLine("key:" + k.Key + " value:" + k.Value);
}
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤