by Steven Applegate
February 3, 2010
This is a nice little technique to easily sort a generic List using delegates. Say you have the following class:
publicclassProduct{ privateint _ProductID; privatestring _Name; privatedecimal _Price; public Product(int productid, string name, decimal price) { _ProductID = productid; _Name = name; _Price = price; } publicint ProductID { get { return _ProductID; } set { _ProductID = value; } } publicstring Name { get { return _Name; } set { _Name = value; } } publicdecimal Price { get { return _Price; } set { _Price = value; } }}
First, we'll create a Product list and fill it with products:
List<Product> products = GetAllProducts();
Now, let's say you want to filter the products, and only get products that have a price of more than $40. You can filter the list by using the FindAll() method, using anonymous delegates instead of predicates:
products = products.FindAll(delegate(Product p) { return p.Price > 40; });
You can sort a generic list the same way. Usually, to sort a custom class, you'd have to have your class inherit from the IComparable interface, and implement your own CompareTo method. But using anonymous delegates, you can use the Sort method any way you want with just a single line of code. This will sort the list by Name ascending:
products.Sort(delegate(Product p1, Product p2) { return p1.Name.CompareTo(p2.Name); });
So there you have it. Using anonymous delegates, you can sort and filter an entire generic list using only two lines of code.A few more examples:
//Filter list to only get products that start with the letter Aproducts = products.FindAll(delegate(Product p) { return p.Name.ToLower().StartsWith("a"); });//Filter over a price rangeproducts = products.FindAll(delegate(Product p) { return (p.Price > 20 && p.Price < 60); });//Sort by Name descendingproducts.Sort(delegate(Product p1, Product p2) { return p2.Name.CompareTo(p1.Name); });