Sorting Object Collections for a Generic List

Below, are examples of how you can sort a generic List<> collection.

This is an example of sorting by Customer.Name ASC.

List<Customer> collection = new List<Customer>();
collection.Sort(delegate(Customer c1, Customer c2)
{
    return c1.Name.CompareTo(c2.Name);
});

This is an example of sorting by MULTIPLE properties. The collection below will sort the collection by Customer.NumberOfLocations DESC, then by Customer.Name ASC.

List<Customer> collection = new List<Customer>();
collection.Sort(delegate(Customer c1, Customer c2)
{
    return c2.NumberOfLocations.CompareTo(c1.NumberOfLocations) + 
        c1.Name.CompareTo(c2.Name);
});

Finding an Object in a Generic List

List<Customer> collection = new List<Customer>();
Customer obj = collection.Find(delegate(Customer p) { return p.CustomerID == 3; });

Finding ALL Matching Objects in a Generic List

List<Customer> collection = new List<Customer>();
List<Customer> matches = collection.FindAll(delegate(Customer p) { return p.State == "KS"; });



 
Copyright 2007. © Inspired Effect ™. All Rights Reserved Home