开发者

Sort collection by order of an array

So I have a collection of Employee objects. I have a list that contains this data:

EmployeeID: 1
Name: Name1

EmployeeID: 2
Name: Name2

EmployeeID: 3
Name: Name3

I run some code to get back a sort order of these employees, and I put the EmployeeIDs in an array: [2,1,3].

How can I take my collection of Employees, and sort them by the array of 开发者_如何学PythonEmployeeIDs?


You would fetch the elements for your array, not sort by the array items.

 var employees = myArray.Select(item => myEmployeeCollection.First(x => x.EmployeeId == item).ToList();

employees would then be a List of the employee objects in the order of your array.


I think this user asked the same question - you can join the two sets based on EmployeeId in a linq query.

Custom sorting with LINQ


You can use Array.IndexOf to order the collection based on the ID index.

Try this:

        var employees = new List<Employee>();
        employees.Add(new Employee{ID = 3, Name="Name1"});
        employees.Add(new Employee{ID = 1, Name="Name2"});
        employees.Add(new Employee{ID = 2, Name="Name3"});

        var orders = new long[]{2, 1, 3};

        var orderedEmployees = employees.OrderBy(e => Array.IndexOf(orders, e.ID));
        orderedEmployees.ToList().ForEach(e => Console.WriteLine(e.ID));


var employees = ...
var employeesByID = employees.ToDictionary(employee => employee.ID);

var sortedIDs = new int[] {2, 1, 3};
var sortedEmployees = sortedIDs.Select(ID => employeesByID[ID]);

The dictionary guarantees the employee lookup's performance will be good even if you have many employees in your collection.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜