我有 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};
我现在有一个整数数组,表示我想要显示数组的顺序
var list = new List<int>();
list.Add(22);
list.Add(62);
list.Add(30);
列表数组对 PeopleList 集合进行排序的正确方法是什么?所以我订购了:
Tom, Jack, Joe
答案 0 :(得分:7)
创建人员对象的ID查找:
var peopleLookup = peopleList.ToDictionary(person => person.Id);
然后,您可以浏览您的ID列表,将每个ID映射到一个人:
var query = list.Select(id => peopleLookup[id]);
答案 1 :(得分:0)
您可以使用list.IndexOf(Id)
。使用LINQ的OrderBy
创建一个新列表
var sorted = peopleList.OrderBy(x => list.IndexOf(x.Id)).ToList();
或使用List<T>.Sort
重新排列列表本身
peopleList.Sort((x, y) => list.IndexOf(x.Id).CompareTo(list.IndexOf(y.Id)));
答案 2 :(得分:-2)
如果收集很大,可能会很慢,但这很有效。
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)));