C# 对集合进行排序
场景1:当我们对一个集合类型使用Sort方法进行排序时,默认情况下Sort方法内部会调用默认比较器,这样排序出来的结果可能并不是我们期望的;
场景2:若是让集合中的元素实现IComparable
1、我们想要按照其它属性进行排序需要进行代码修改
2、集合中的元素所属类型我们可能无法对其进行修改
综上,集合排序的方式大致可以分为以下三种:
第一种:使用Comparison进行排序
第二种:针对集合元素类型写一个实现IComparer
第三种:使用OrderBy方法,返回IEnumerable
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
namespace SortListDemo
{
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public override string ToString()
{
return $"{this.Name}{this.Price}";
}
}
internal class Program
{
static void Main(string[] args)
{
var products = new List<Product>();
products.Add(new Product() { Name = "小米", Price = 3.58d });
products.Add(new Product() { Name = "大米", Price = 1.58d });
products.Add(new Product() { Name = "黑米", Price = 2.58d });
SortByComparison(products);
SortByIComparer(products);
SortByLinq(products);
Console.ReadLine();
}
private static void SortByComparison(List<Product> products)
{
//第一种使用Comparison进行排序
products.Sort(new Comparison<Product>((x, y) =>
{
return x.Price.CompareTo(y.Price);
}));
Action<Product> print = System.Console.WriteLine;
foreach (var item in products)
{
print(item);
}
}
private static void SortByIComparer(List<Product> products)
{
//第二种使用自定义的比较器
var comparer = new ProductSortByPriceComparer();
products.Sort(comparer);
Action<Product> print = System.Console.WriteLine;
foreach (var item in products)
{
print(item);
}
}
private static void SortByLinq(List<Product> products)
{
//第三种使用扩展方法Linq
foreach (var item in products.OrderBy(x => x.Price))
{
Console.WriteLine(item);
}
}
}
class ProductSortByPriceComparer : IComparer<Product>
{
public int Compare(Product x, Product y)
{
return x.Price.CompareTo(y.Price);
}
}
}
以上便是对集合进行排序的三种操作,使用Sort排序会影响源集合,使用Orderby排序不会影响原集合。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异