C# Sorting a List based on the sequence of values from another List (different classes)

.net, c#, linq

Solution

You can join the two lists on the IDs:

var query = from x in data
            join y in dataToSort on x.ID equals y.ID
            select y;

var result = query.ToList();

This keeps the order of the first list `data`.

You can also easily combine the two lists this way:

var query = from x in data
            join y in dataToSort on x.ID equals y.ID
            select new
            {
                x.Name,
                x.ID,
                y.retrievedData,
                y.timeStamp,
            };

var result = query.ToList();

Problem

I'm currently stuck at a problem where I have 2 Lists, and I want to sort the second List according to a value from the first List, here is an example: ``` public class data { public string Name{get; set;} public int ID{get; set} } public class dataToSort { public int ID{get; set;} public string retrievedData{get; set} public string timeStamp{get; set} } ``` So lets say I have 2 List objects, one for data and one for dataToSort, their contents below: ``` data: "Alpha", "80" dataToSort: "21", "XA", "YA" "Beta", "47" "47", "XB", "YB" "Charlie", "153" "80", "XC", "YC" "Delta", "21" "153","XD", "YD" ``` So what I want to do is to make the order of dataToSort equal to the order of the IDs in data, like this: ``` dataToSort: "80", "XC", "YC" "47", "XB", "YB" "153","XD", "YD" "21", "XA", "YA" ``` I have tried googling for a way to Sort these but all the LINQ syntax confuses me and I have problems due to the difference in classes of each object :( The only way I can think of is to have a for loop to get the index of one List's ID and do something like a bubble sort, but its too much of a hassle and also inefficient. Help is greatly appreciated!

Original source