2014-01-22 4 views
4

목록을 'n'개의 하위 목록으로 분할하고 싶습니다.C# - 목록을 n 개의 하위 목록으로 분할

본인에게는 양식 교사 목록과 학생 목록이 있습니다. 모든 학생은 한 명의 양식 교사에게 배정되며 각 양식 교사는 한 명 이상의 학생을 가질 수 있습니다. 양식 교사 목록은 동적입니다. 양식의 확인란 선택에 따라 채워집니다 (예 : 목록에 1, 3, 6 등이있을 수 있음).

//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 명의 Form 교사가 있다고 가정 해 봅시다. 목록을 3 개의 하위 목록으로 나눌 수는 없지만 결국 3 명의 학생 목록으로 끝납니다.

정말 도움이 될 것입니다. 나는 가능한 해결책을 찾았지 만, 목록의 크기가 아닌 'n'크기의 목록으로 끝날 때마다. 이전에이 질문에 답한 적이 있다면 그 대답의 방향을 알려주십시오.

+1

는이에 대한 GROUPBY에 찾고 시도? – Codeman

+1

낙타를 사용하지 마십시오. MethodNames ...'splitList()'='SplitList()'... => http://msdn.microsoft.com/en-us/library/4df752aw(v=vs. 71) .aspx – Shiva

답변

15

같은 수의 요소를 사용하여 목록을 n 개의 파트로 나누려고합니까?

var splitStudentList = studentList.Select((s, i) => new { s, i }) 
            .GroupBy(x => x.i % numFormTeachers) 
            .Select(g => g.Select(x => x.s).ToList()) 
            .ToList(); 

또는 당신은 그렇게 할 자신의 확장 메서드를 만들 수 있습니다

GroupBy을보십시오. 나는 나의 blog에 그것을 바로하는 방법을 기술했다 : 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

관련 문제