Project DescriptionAn extension method for IEnumerable<T> that will sort the IEnumerable based on a list of keys.
Suppose you have a list of IDs {10, 5, 12} and want to use LINQ to retrieve all People from the DB with those IDs in that order, you want this extension.
Sort is binary so it's fast
Background
More detailed background information and speed tests are available on my blog at
http://blog.statichippo.com/archive/2010/04/07/ordertolist-fix-for-linq-to-sql-order-dilemma.aspxSuppose you have a list of IDs of People. These IDs are ints (but could be any IComparable) and stored in a List<int> called
PeopleIDs. If you want to select all the People from the database using LINQ that have these IDs you would just do something like:
IEnumerable<Person> selectedPeople = dataContext.People.Where(x => PeopleIDs.Contains(x.ID));
However, that would retrieve all People with those IDs regardless of the ordering. For example, if
PeopleIDs contained the values { 109, 45, 37, 223, 759, 2 } and you wanted the People selected to be ordered in that same order, the above code wouldn't work for you. This extension method, however, provides a fast way of ordering the results according to that list of IDs.