can I sort a list based on another list in C# [closed]

say I have a list (List_1) of ints: {3, 1, 2}

then I sort that list to be: {1, 2, 3}

can i sort another list of strings (List_2): {“eg1”, “eg2”, “eg3”}

can i sort List_2 based on the sorting of List_1, for example: list_1 goes from {3, 1, 2} to {1, 2, 3} then list_2 goes from {“eg1”, “eg2”, “eg3”} to {“eg2”, “eg3”, “eg1”}

is this possible in c#?

Answer

Create a class that contains both items, and then sort that list:

class Item
{
    public int Id {get;set}
    public string Text {get;set;}
}

var unsorted = new List<Item>
{
    new Item{Id = 3, Text = "eg3"},
    new Item{Id = 1, Text = "eg1"},
    new Item{Id = 2, Text = "eg2"},
}

var sorted = unsorted.OrderBy(x=>x.Id);

Further examples of OrderBy here: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby

Leave a Reply

Your email address will not be published. Required fields are marked *