4

Consider a database table holding names, with three rows:

SubjectID      StudentName
---------      -------------
 1             Peter
 2             Paul
 2             Mary

Is there an easy way to turn this into a single string in entity framework? something like this:

SubjectID       StudentName
----------      -------------
1               Peter
2               Paul, Mary

Check this link to more information.

Community
  • 1
  • 1
Hossein Moradinia
  • 6,116
  • 14
  • 59
  • 85

1 Answers1

7

You can use GroupBy to group your students by subject:

var result = StudentSubjects
                .GroupBy(x => x.SubjectID)
                .Select(x => new 
                    { 
                        Subject = x.Key, 
                        Names = String.Join(", ", x.Select(n => n.Name)) 
                    });

I have used String.Join to concatenate the list of names.

Dave New
  • 38,496
  • 59
  • 215
  • 394