[英]In C#, how can I sort a collection of objects by a seperate int array?
I have a collection of Person objects and a Person object has an id property. 我有一个Person对象的集合,一个Person对象具有一个id属性。
var peopleList = new List<Person>();
peopleList .Add(new Person(){Name = Joe, Id = 30};
peopleList .Add(new Person(){Name = Tom, Id = 22};
peopleList .Add(new Person(){Name = Jack, Id = 62};
I now have an array of integers that represents the ordering that i want to display the array 我现在有一个整数数组,它表示我要显示该数组的顺序
var list = new List<int>();
list.Add(22);
list.Add(62);
list.Add(30);
what is the correct way of sorting the PeopleList collection by the List array? 通过List数组对PeopleList集合进行排序的正确方法是什么? so I get an ordering of: 所以我得到了以下命令:
Tom, Jack, Joe
Create a lookup of ids to person objects: 创建对人员对象的ID的查找:
var peopleLookup = peopleList.ToDictionary(person => person.Id);
Then you can go through your list of IDs, mapping each to a person: 然后,您可以浏览ID列表,将每个ID映射到一个人:
var query = list.Select(id => peopleLookup[id]);
You can use list.IndexOf(Id)
. 您可以使用list.IndexOf(Id)
。 Use LINQ's OrderBy
to create a new list 使用LINQ的OrderBy
创建新列表
var sorted = peopleList.OrderBy(x => list.IndexOf(x.Id)).ToList();
Or use List<T>.Sort
to reorder the list itself 或使用List<T>.Sort
对列表本身重新排序
peopleList.Sort((x, y) => list.IndexOf(x.Id).CompareTo(list.IndexOf(y.Id)));
Might be slow if collection is huge, but this works. 如果收集量很大,可能会很慢,但这是可行的。
var peopleList = new List<Person>();
peopleList.Add(new Person() { Name = "Joe", Id = 30 });
peopleList.Add(new Person() { Name = "Tom", Id = 22 });
peopleList.Add(new Person() { Name = "Jack", Id = 62 });
var list = new List<int>();
list.Add(22);
list.Add(62);
list.Add(30);
peopleList.Sort((x, y) => list.IndexOf(x.Id).CompareTo(list.IndexOf(y.Id)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.