-1

I am new to MVC. I have a Student View Model StudentVM with few properties.

public class StudentVM
{
    public int studentid { get; set; }
    public string Name { get; set; }
    public string Grade { get; set; }
    public int Age { get; set; }
}

In my Controller I have added few values to the list say

 List<StudentVM> studentList = new List<StudentVM>();
        studentList.Add(new StudentVM {studentid=1,Name="John",Grade="A",Age=20 });
        studentList.Add(new StudentVM { studentid = 1, Name = "John", Grade = "A", Age = 20 });
        studentList.Add(new StudentVM { studentid = 2, Name = "Alex", Grade = "A", Age = 21 });
        studentList.Add(new StudentVM { studentid = 3, Name = "David", Grade = "A", Age = 19 });
        studentList.Add(new StudentVM { studentid = 4, Name = "Joe", Grade = "B", Age = 23 });
        studentList.Add(new StudentVM { studentid = 5, Name = "Mark", Grade = "B", Age = 22 });
        studentList.Add(new StudentVM { studentid = 6, Name = "Henry", Grade = "C", Age = 18 });
        studentList.Add(new StudentVM { studentid = 7, Name = "Gergin", Grade = "C", Age = 20 });
        studentList.Add(new StudentVM { studentid = 8, Name = "Jade", Grade = "C", Age = 25 });

        var listOfStudents = studentList;

Notice that some lists has same Grade. (the first four lists has Grade="A")

What I need is another viewModel list to carry the same list but grouped by Grade.

Considering my example, I need the new ViewModel list to contain 3 lists 1st list must contain 4 lists (As there are 4 students with the same grade). 2nd list must contain 2 lists with Grade B 3rd list must contain 3 lists with Grade C

Is there any way to do this?

1
  • 7
    "Is there any way to do this"? Yes. Here's a hint: Enumerable.GroupBy(). Go forth and conquer. We're not going to do your homework for you here.
    – itsme86
    Feb 24, 2017 at 15:37

1 Answer 1

1

So to separate them by grade you can do this

var groupedByGrade = studentList.GroupBy(x => x.Grade);

then if you want to make each of those groups lists

var studentsByGrade = groupedByGrade.Select(x => x.ToList()).ToList();

then if you really want a List containing Lists of one student each

var listsOfListOfStudents = studentsByGrade.Select(x => x.Select(y => new List<StudentVM> { y }).ToList()).ToList();

if you put them all together you can do this

var listsOfListOfStudents = studentList.GroupBy(x => x.Grade).Select(x => x.Select(y => new List<StudentVM> { y }).ToList()).ToList();
1
  • Thanks man. You are awesome ! Feb 25, 2017 at 13:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.