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
  • 5,936
  • 14
  • 57
  • 85

1 Answers1

6

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
  • 36,059
  • 54
  • 198
  • 383