views:

47

answers:

1

What would be the fastest way to sort a list that contains a list of objects, based upon another list? An example follows:

Say I have multiple lists of employees. Each individual list has a common property value, say "Department". So I have a list of employees, in one list they all have the department string value of "Sales". In another list all the objects have a department value of "Finance". These lists of employees are then contained in a list which holds them all.

I have a second list, which should drives the sort order of the employee lists. The second list simply contains a list of strings like, "Finance", "Sales", "IT" and so on. I'd like my lists of customers to be sorted in the order of "Finance", "Sales", etc.

I'm using VB.NET in .NET 2.0

Cheers!

A: 

EDIT: Sorry, didn't notice that you had mentioned VB.

This is isn't the most efficient way, but here's one way to do it:

List<List<Employee>> employeeLists = ...
List<string> departments = ...

// implicitly List<List<Employee>>
var sortedEmpLists = employeeLists
                   .OrderBy(eList => departments.IndexOf(eList.First().Department))
                   .ToList();

Essentially, the idea is to declare that a sub-list of employees' order depends on the order of its first member's department. Of course, this depends on the following assumptions, which I think hold true in your scenario:

  1. All employees in a sub-list belong to the same department.
  2. All sub-lists of employees contain at least one employee.
  3. All departments referred to in the employee-lists are present in the departments list.

If you want an in-place sort:

employeeLists.Sort((eList1, eList2) =>
                  departments.IndexOf(eList1.First().Department)
                             .CompareTo(departments.IndexOf(eList2.First().Department)));

EDIT: Here's a .NET 2.0 version (C#):

Comparison<List<Employee>> comp = 
                            delegate(List<Employee> eList1, List<Employee> eList2)
                            {
                               string d1 = departments.IndexOf(eList1[0].Department);
                               string d2 = departments.IndexOf(eList2[0].Department);
                               return d1.CompareTo(d2);                                         
                            };
employeeLists.Sort(comp);

Of course, you could always write an IComparer<List<Employee>> too.

Ani
I can't use LINQ in .NET 2.0
Ek0nomik
@Ek0nomik: Edited. Sorry, I don't know VB.NET, so I can't provide the *exact* code you need.
Ani