2014-01-22 87 views
4

我想將一個列表拆分成'n'個子列表。C# - 將列表拆分成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」個列表。如果這個問題之前已經得到解答,請將問題指向該答案的方向。

+1

您是否嘗試過尋找到的GroupBy這個? – Codeman

+1

Please,no camelCase-ing MethodName ...'splitList()'='SplitList()'... See => http://msdn.microsoft.com/en-us/library/4df752aw(v=vs。 71).aspx – Shiva

回答

15

您試圖將您的列表分割成具有相同數量元素的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(); 
+0

完美。謝謝! – normgatt