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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With