This is a little lengthy, but it should help out. I wasn't sure about the
Orders class so I just created a simple class with an orderId field, but the
rest are based on your example.
Here's the Orders class:
public class Orders
{
private int _orderId;
public Orders() { }
public Orders(int orderId)
{
this.OrderId = orderId;
}
// Properties
public int OrderId
{
get { return this._orderId; }
set { this._orderId = value; }
}
}
Here's the Customer and CustomerCollection classes:
public class Customer : List<Orders>
{
private string _customerName;
public Customer() { }
public Customer(string customerName)
{
this.CustomerName = customerName;
}
// Properties
public string CustomerName
{
get { return this._customerName; }
set { this._customerName = value; }
}
}
public class CustomerCollection : List<Customer>
{
}
Here's the IComparer<> to allow sorting by a customer's name.
To create a comparer, I created a simple public class implementing
IComparer<> as follows which simply returns the result string.Compare(). (The
class implementing IComparer<> can also be nested if needed as suggested in
another post.):
public class CompareByCustomerName : IComparer<Customer>
{
public int Compare(Customer x, Customer y)
{
return string.Compare(x.CustomerName, y.CustomerName);
}
You can use a new instance of this comparer and pass it to a collection's
sort method as shown in the following example. I just copied and pasted the
main method from a simple app I made to illustrate sorting by customer name:
static void Main(string[] args)
{
// Create three customers
// and fill with orders.
Customer cust1 = new Customer("John Smith");
cust1.AddRange(new Orders[]{
new Orders(101),
new Orders(102)});
Customer cust2 = new Customer("Wendy Johnson");
cust2.AddRange(new Orders[]{
new Orders(250),
new Orders(287)});
Customer cust3 = new Customer("Brad Michaels");
cust3.AddRange(new Orders[]{
new Orders(145),
new Orders(309)});
// Add customers to new CustomerCollection
CustomerCollection custCollection = new CustomerCollection();
custCollection.Add(cust1);
custCollection.Add(cust2);
custCollection.Add(cust3);
// Print out the customers in the
// collection before sorting.
Console.WriteLine("Before sort:");
foreach (Customer customer in custCollection)
Console.WriteLine(customer.CustomerName);
Console.WriteLine("\n\n");
// Sort customers using the CustomerCollection's
// sort method inherited from List and
// passing a new instance of CompareCustomerByName.
// Then print out each customer's name after sorting.
custCollection.Sort(new CompareByCustomerName());
Console.WriteLine("After sort by customer name:");
foreach (Customer customer in custCollection)
Console.WriteLine(customer.CustomerName);
// Press Enter before terminating
Console.ReadLine();
}
Hopefully this helps, and again, sorry about the length.
Robert Wingard