开发者

Sort generic list based upon a different list

开发者 https://www.devze.com 2023-01-22 17:08 出处:网络
What would be the fastest way to sort a list that contains a list of objects, based upon another list?An example follows:

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 lis开发者_如何学JAVAt 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消