我有以下对象结构 -
public class Student
{
public int RollNumber { get; set; }
public string Name { get; set; }
public string Division { get; set; }
}
另外我有2个对象列表如下:
1)主列表 -
var masterList = new List<Student>
{
new Student {RollNumber = 1, Name = "Jim", Division = "A"},
new Student {RollNumber = 10, Name = "Mike", Division = "A"},
new Student {RollNumber = 8, Name = "Peter", Division = "A"},
new Student {RollNumber = 4, Name = "Sandy", Division = "A"},
new Student {RollNumber = 7, Name = "Michale", Division = "A"}
};
2)SubList
var subList = new List<Student>
{
new Student {RollNumber = 4, Name = "Sandy", Division = "A"},
new Student {RollNumber = 7, Name = "Michale", Division = "A"},
new Student {RollNumber = 1, Name = "Jim", Division = "A"},
new Student {RollNumber = 10, Name = "Mike", Division = "A"}
};
我想在我的子列表中对主列表中的对象顺序进行排序,就像应用排序后,SubList中的对象顺序应为 -
new Student {RollNumber = 1, Name = "Jim", Division = "A"},
new Student {RollNumber = 10, Name = "Mike", Division = "A"},
new Student {RollNumber = 4, Name = "Sandy", Division = "A"},
new Student {RollNumber = 7, Name = "Michale", Division = "A"}
是否有可能实现这样的排序逻辑?
答案 0 :(得分:1)
假设RollNumber是识别字段:
<form method="POST" action="">
<?php
xxx1();
xxx2();
?>
</form>
答案 1 :(得分:1)
//假设没有重复的记录。
var masterList = new List<Student>
{
new Student {RollNumber = 1, Name = "Jim", Division = "A"},
new Student {RollNumber = 10, Name = "Mike", Division = "A"},
new Student {RollNumber = 8, Name = "Peter", Division = "A"},
new Student {RollNumber = 4, Name = "Sandy", Division = "A"},
new Student {RollNumber = 7, Name = "Michale", Division = "A"}
};
var subList = new List<Student>
{
new Student {RollNumber = 4, Name = "Sandy", Division = "A"},
new Student {RollNumber = 7, Name = "Michale", Division = "A"},
new Student {RollNumber = 1, Name = "Jim", Division = "A"},
new Student {RollNumber = 10, Name = "Mike", Division = "A"}
};
List<Student> sortedList = new List<Student>();
foreach (var item in masterList.Select(x => x.RollNumber))
{
if (subList.Where(x => x.RollNumber == item).FirstOrDefault() != null)
sortedList.Add(subList.Where(x => x.RollNumber == item).First());
}
答案 2 :(得分:0)
当然有可能,但你应该问自己什么是学生。因为列表当前不包含与对象标识相同的学生。
如果是,即如果masterList
和subList
确实包含相同的对象,您只需按顺序排序
subList.Sort((s1, s2) => masterList.IndexOf(s1).CompareTo(masterList.IndexOf(s2));
否则你必须识别学生,例如使用RollNumber。
编辑:与kaarel的答案相比,这个解决方案会对列表进行排序,而kaarel的解决方案可能更容易阅读。