通过自定义比较器排序(C#版)

时间:2021-07-29 07:58:19

一、方法概述

自定义比较器需要实现接口IComparer<T>

二、示例过程

1、新建一个Product产品类

    /// <summary>
/// 产品类
/// </summary>
public class Product
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 价格
/// </summary>
public Double Price { get; set; }
/// <summary>
/// 编号
/// </summary>
public int Num { get; set; }
}

2、新建一个Product对象并赋值

List<Product> products = new List<Product>();
products.Add(new Product() { Name = "pro1", Price = 2.4, Num = });
products.Add(new Product() { Name = "pro2", Price = 4.6, Num = });
products.Add(new Product() { Name = "pro3", Price = 1.8, Num = });
products.Add(new Product() { Name = "pro4", Price = 25.2, Num = });

3、创建比较器

(1) 产品价格比较器:

    /// <summary>
/// 产品价格比较器
/// </summary>
public class ProductPriceComparer : IComparer<Product>
{
public int Compare(Product x,Product y)
{
if (x == null && y == null) return ;
if (x == null) return -;
if (y == null) return ;
var diff = x.Price - y.Price;
if (diff > ) return ;
if (diff < ) return -;
return ;
}
}

(2) 产品名称比较器:

    /// <summary>
/// 产品名称比较器
/// </summary>
public class ProductNameComparer : IComparer<Product>
{
public int Compare(Product x,Product y)
{
if (x == null && y == null) return ;
if (x == null) return -;
if (y == null) return ;
return x.Name.CompareTo(y.Name);
}
}

(3) 产品编号比较器:

    /// <summary>
/// 产品编号比较器
/// </summary>
public class ProductNumComparer : IComparer<Product>
{
public int Compare(Product x, Product y)
{
if (x == null && y == null) return ;
if (x == null) return -;
if (y == null) return ;
return x.Num-y.Num;
}
}

4、打印输出结果的方法

        /// <summary>
/// 打印结果
/// </summary>
/// <param name="products"></param>
public static void PrintResult(List<Product> products)
{
Console.WriteLine("开始打印");
foreach (var product in products)
{
Console.WriteLine($"name:{product.Name},price:{product.Price},num:{product.Num}");
}
Console.WriteLine("打印完毕");
Console.WriteLine("----------分割线----------------------");
}

5、通过比较器排序并打印出结果

    products.Sort(new ProductNameComparer());
Console.WriteLine("根据名称排序:");
PrintResult(products); products.Sort(new ProductNumComparer());
Console.WriteLine("根据编号排序:");
PrintResult(products); products.Sort(new ProductPriceComparer());
Console.WriteLine("根据价格排序:");
PrintResult(products);

6、输出结果

通过自定义比较器排序(C#版)