集合的过滤和排序
这章主要设计list集合的FindAll,sort扩展方法实现机会的过滤或排序。在对集合处理时,最好用的系统提供的扩展方法。
过滤
List<T>
的扩展方法 FindAll,参数类型为委托,传入过滤函数。
排序
排序有三种实现方式
下面是过滤与拍下的代码,可以相应注释查看相应运行结果。
public class Book: IComparable<Book>
{
public string Title { get; set; }
public DateTime publishedDate { get; set; }
public decimal Price { get; set; }
public override string ToString()
{
return string.Format("Title:{0},Published Date:{1},Price:{2}",Title,publishedDate.ToString("yyyy-MM-dd"),Price);
}
//02只能按照一种规则排序
public int CompareTo(Book other)
{
return Price.CompareTo(other.Price);
}
}
public class BookCompareByPrice : IComparer<Book>
{
public int Compare(Book x, Book y)
{
return x.Price.CompareTo(y.Price);
}
}
//调用
static void Main(string[] args)
{
List<Book> bookList = new List<Book>() {
new Book() {Title ="Python编程 从入门到实践",publishedDate=new DateTime(2016,7,1),Price=70.10m },
new Book() {Title ="数学之美(第二版)",publishedDate=new DateTime(2014,11,1),Price=39.30m },
new Book() {Title ="算法图解 (图灵程序设计丛书)",publishedDate=new DateTime(2017,9,1),Price=29.30m },
new Book() {Title ="微服务设计 (图灵程序设计丛书)",publishedDate=new DateTime(2016,10,1),Price=29.99m },
new Book() {Title ="JavaScript高级程序设计(第3版)",publishedDate=new DateTime(2012,3,1),Price=69.30m },
};
//01过滤
/*
List<Book> filterResult = bookList.FindAll(item => item.Title.Contains("图灵"));
foreach(Book b in filterResult)
{
Console.WriteLine(b.ToString());
}
*/
//02 第一种拍下,Book实现 IComparable<Book> 接口
//02只能按照一种规则排序
//bookList.Sort();
// 02 添加比较器,
// 每种比较规则需要添加一个类,代码乱
BookCompareByPrice compareByPrice = new BookCompareByPrice();
bookList.Sort(compareByPrice);
// 最好排序方法直接传入比较的方法
//bookList.Sort((x, y) => x.Price.CompareTo(y.Price));
//bookList.Sort((x, y) => x.publishedDate.CompareTo(y.publishedDate));
foreach (Book b in bookList)
{
Console.WriteLine(b.ToString());
}
Console.ReadKey();
}