Giancarlo
Giancarlo

Reputation: 399

Grouping/sorting with Linq

I've got this list with student grades:

Grade Student
10 John
10 Mary
9 Peter
9 Allison

And I want to group them like this:

Grade Students
10 John, Mary
9 Peter, Allison

So I got this Linq command:

var gradesAndStudents = studentsGrades.GroupBy(p => p.grade, p => p.student,
    (key, g) => new { Grade = key, Students = g.ToList() });

So now the result is grouped and sorted and the Grade shows all students with their grades:

Grade Students
10 10, John
10, Mary
9 9, Peter
9, Allison

But how do I get the students name only as a string?

Upvotes: 0

Views: 76

Answers (3)

Feras Salim
Feras Salim

Reputation: 438

Try this

var gradesAndStudents = from p in studentsGrades
              group p.student by p.grade into g
              select new { Grade= g.Key, Students =string.Join(", ", g.ToList()) };

Upvotes: 2

Anton Kovachev
Anton Kovachev

Reputation: 347

You can try this

var studentsByGrades = studentGrades.GroupBy(sg => sg.Grade).Select(sg => KeyValuePair.Create(sg.Key, sg.Select(s => s.Name))).ToList();

In this case, studentsByGrades will be a list of key-value pairs with a key the grade and the value list of student names from that grade i.e. a list of strings. Or you can try something like this

 var studentsByGrades = studentGrades.GroupBy(sg => sg.Grade).ToDictionary(sg => sg.Key, sg => sg.Select(s => s.Name));

in the second example, studentsByGrades will be a dictionary. The keys of the dictionary will be the grades and the values will be a lists with the student names from that grade.

Upvotes: 0

Nateous
Nateous

Reputation: 787

Here's how I would do this:

var gradesAndStudents = studentsGrades
   .GroupBy(p => p.grade, p => p.student, 
           (key, g) => new { Grade = key, Students = string.Join(", ", g.ToList()) });

Once you have your list of student names, you can join them with string.Join

Upvotes: 0

Related Questions