首先定义一个产品类
namespace ChapterOneDemo.Model
{
public class Product
{
public Product(string name, decimal price)
{
this.Name = name;
this.Price = price;
}
public string Name { get; set; }
public decimal Price { get; set; }
}
}
在C# 1中,定义一个ICompare的实现类,然后使用ArrayList.Sort进行排序
缺点是当向ArrayList中添加不是Product类型的数据时,编译器是不会报错的
但是在ICompare的实现类中会出现转换异常
//初始化数组
public static ArrayList GetSampleProductsForCSharpOne()
{
ArrayList list = new ArrayList();
list.Add(new Product("West Side Story", 9.99m));
list.Add(new Product("Assassins", 14.99m));
list.Add(new Product("Frogs", 13.99m));
list.Add(new Product("Sweeney Todd", 10.99m));
return list;
}
//定义Compare
class ProductNameComparerForCSharpOne : IComparer
{
public int Compare(object x, object y)
{
Product first = (Product)x;
Product second = (Product)y;
return first.Name.CompareTo(second.Name);
}
}
//初始化数据
ArrayList productSample_CShareOne = GetSampleProductsForCSharpOne();
productSample_CShareOne.Sort(new ProductNameComparerForCSharpOne());
在C# 2 中,可以使用泛型,不需要进行强制转换
//初始化数据
public static List<Product> GetSampleProducts()
{
List<Product> list = new List<Product>();
list.Add(new Product("West Side Story", 9.99m));
list.Add(new Product("Assassins", 14.99m));
list.Add(new Product("Frogs", 13.99m));
list.Add(new Product("Sweeney Todd", 10.99m));
return list;
}
//定义ICompare的实现类,并且传入委托类型为Product
class ProductNameComparerForCSharpTwo : IComparer<Product>
{
public int Compare(Product x, Product y)
{
return x.Name.CompareTo(y.Name);
}
}
//初始化数据
var productSample = GetSampleProducts();
productSample.Sort(new ProductNameComparerForCSharpTwo());
同样在C# 2我们也可以使用委托的方式来实现,
//初始化数据
var productSample = GetSampleProducts();
//不要再定义ICompare的实现类,直接使用委托的方式实现
productSample.Sort(delegate (Product x, Product y)
{
return x.Name.CompareTo(y.Name);
});
C# 3 使用Lambda表达式
List<Product> productSample = GetSampleProducts();
productSample.Sort((x, y) => x.Name.CompareTo(y.Name));
同样在C# 3 中我们也可以使用Linq中的OrderBy方法实现
Linq是C# 3的核心
//初始化数据
List<Product> productSample = GetSampleProducts();
productSample = productSample.OrderBy(r => r.Name).ToList();
以上实例来自于《深入理解C#(第3版)》一书
希望将本书学习中曾经不理解或觉得将来有作用的部分摘录下来,以备不时之需,也希望能和大家一起分享