Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a List<T> by another List<T>

Tags:

c#

linq

My model is:

class Person
{
    public int Id {get; set; }
    public string Name {get; set; }
}

I have two collections. And I would like to sort toBeSortedList like etalonList:

List<Person> etalonList = new List<Person>()
{
     new Person() { Id=10, Name="Jon"},
     new Person() { Id=4, Name="Ben"},
     new Person() { Id=11, Name="Magnus"},
     new Person() { Id=8, Name="Joseph"},
};

List<Person> toBeSortedList = new List<Person>()
{
     new Person() { Id=11, Name="Magnus"},
     new Person() { Id=4, Name="Ben"},                
     new Person() { Id=10, Name="Jon"},
     new Person() { Id=8, Name="Joseph"},
};

I've tried:

var orderedByIdList = tobeSortedList.OrderBy(x => etalonList.IndexOf(x.Id));

But I've met a such error:

cannot convert from 'int' to 'SOConsoleApplication.Person'

Maybe you have another suggestions?

like image 723
StepUp Avatar asked Mar 16 '26 18:03

StepUp


1 Answers

I would first create a dictionary from etalonList in order to speed up sorting:

int index;
var etalonDictionary = etalonList.ToDictionary(k => k.Id, v => index++);

Then find back the ID from the dictionary and use that for sorting:

var sortedList = toBeSortedList.OrderBy(x => etalonDictionary[x.Id]).ToList();
like image 184
Patrick Hofman Avatar answered Mar 18 '26 07:03

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!