我想将一个列表分成n个子列表。
我有一个名单老师和一个学生名单。每个学生分配给一位表格老师,每位表格老师可以拥有多位学生。表单教师的列表是动态的-根据表单上的复选框选择进行填充(即:列表中可能有一个,三个,六个等)。
//A method to assign the Selected Form teachers to the Students
private void AssignFormTeachers(List<FormTeacher> formTeacherList, List<Student> studentList)
{
int numFormTeachers = formTeacherList.Count;
//Sort the Students by Course - this ensures cohort identity.
studentList = studentList.OrderBy(Student => Student.CourseID).ToList();
//Split the list according to the number of Form teachers
List<List<Student>> splitStudentList = splitList(numFormTeachers , studentList);
该splitList()
方法是我尝试将列表拆分为学生列表列表的地方,但是遇到了问题。假设有3位表单老师-我似乎无法将列表分为3个子列表,而最终得到3个学生列表。
我真的很感谢您的帮助。我一直在寻找一种可能的解决方案,但是每次我最终得到的列表大小都是'n',而不是数量为'n'的列表时。如果以前已经回答了这个问题,请指出该回答的方向。
您正在尝试将列表划分n
为元素数量相等的部分吗?
尝试GroupBy
:
var splitStudentList = studentList.Select((s, i) => new { s, i })
.GroupBy(x => x.i % numFormTeachers)
.Select(g => g.Select(x => x.s).ToList())
.ToList();
或者,您可以创建自己的扩展方法来执行此操作。我已经在我的博客上描述了正确的方法:使用LINQ对集合进行分区:不同的方法,不同的性能,相同的结果。
public IEnumerable<IEnumerable<T>> Partition<T>(IEnumerable<T> source, int size)
{
var partition = new List<T>(size);
var counter = 0;
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
partition.Add(enumerator.Current);
counter++;
if (counter % size == 0)
{
yield return partition.ToList();
partition.Clear();
counter = 0;
}
}
if (counter != 0)
yield return partition;
}
}
用法:
var splitStudentList = studentList.Partition(numFormTeachers)
.Select(x => x.ToList())
.ToList();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句