Sort in-memory list by another in-memory list

asp.net, c#, linq, linq-to-sql

Solution

First, lets assign an index to each item in `sortOrder`:

var sortOrderWithIndices = sortOrder.Select((x, i) => new { path = x, index = i });

Next, we join the two lists and sort:

var dataItemsOrdered =
 from d in dataItems
 join x in sortOrderWithIndices on d.Path equals x.path //pull index by path
 orderby x.index //order by index
 select d;

This is how you'd do it in SQL as well.

Problem

Is possible to sort an in-memory list by another list (the second list would be a reference data-source or something like this) ? ``` public class DataItem { public string Name { get; set; } public string Path { get; set; } } // a list of Data Items, randomly sorted List<DataItem> dataItems = GetDataItems(); // the sort order data source with the paths in the correct order IEnumerable<string> sortOrder = new List<string> { "A", "A.A1", "A.A2", "A.B1" }; // is there a way to tell linq to sort the in-memory list of objects // by the sortOrder "data source" dataItems = dataItems.OrderBy(p => p.Path == sortOrder).ToList(); ```

Original source