C# - 将列表拆分为 n 个子列表

标签 c# linq

我想将一个列表分成“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 位类(class)教师 - 我似乎无法将列表拆分为 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();

或者您可以创建自己的扩展方法来执行此操作。我已经在我的博客上描述了如何正确地做到这一点:Partitioning the collection using LINQ: different approaches, different performance, the same result .

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();

关于C# - 将列表拆分为 n 个子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21295639/

相关文章:

c# - 比较两个对象列表 C#

c# - Wpf:在多个控件上应用自定义样式的工具提示

c# - LINQ to Entities 无法识别方法 'System.DateTime ToDateTime(System.String)'

sql - 如何获取此 sql 查询并将其转换为 nhibernate 查询

c# - 将 LINQ 中的循环缩短为一个 QUERY

c# - 使用 lambda 表达式从 List<int> 中获取 N 个最大数字

c# - 结合序列化和语法解析的方法?

c# - 将 MenuItems 命令绑定(bind)到 UserControls DataContext

c# - Linq2SQL : Select only some columns, 但仍然可以提交更改

c# - linq 查询可能缺少一些 from 值