阅读量:3
要对复杂对象字典进行排序,可以使用LINQ查询和Lambda表达式来根据特定的属性对对象进行排序。以下是一个示例代码,演示如何对包含复杂对象的字典进行排序:
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
Dictionary<int, Person> dict = new Dictionary<int, Person>
{
{1, new Person { Name = "Alice", Age = 25 }},
{2, new Person { Name = "Bob", Age = 30 }},
{3, new Person { Name = "Charlie", Age = 20 }}
};
var sortedDict = dict.OrderBy(x => x.Value.Age).ToDictionary(x => x.Key, x => x.Value);
foreach (var item in sortedDict)
{
Console.WriteLine($"Key: {item.Key}, Name: {item.Value.Name}, Age: {item.Value.Age}");
}
}
}
在上面的示例中,我们定义了一个名为Person的类,该类具有Name和Age属性。然后我们创建了一个字典dict,其中包含整数键和Person对象值。我们使用LINQ的OrderBy方法根据Person对象的Age属性对字典进行排序,并将排序后的结果转换为新的字典sortedDict。最后,我们遍历sortedDict并打印出每个元素的键和值。
你可以根据自己的需求修改排序的逻辑,例如按照Name属性或者自定义的排序规则进行排序。
以上就是关于“C#如何对复杂对象字典进行排序”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm