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.

7
  • 1
    1) what have you tried? 2) the inputs/outputs don't match! 3) your output example is arbitrary. what's the logic? Commented May 28, 2013 at 12:33
  • please check stackoverflow.com/questions/194852/… for more info Commented May 28, 2013 at 12:35
  • 1
    That link is irrelevant. Commented May 28, 2013 at 12:36
  • I change output in my question Commented May 28, 2013 at 12:37
  • Your example output still defies your request. What do you want, and where are you stuck with it? Commented May 28, 2013 at 12:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I got error LINQ to Entities does not recognize the method 'System.String Join
This code wouldn't work unless you call ToList() or ToListAsync(cancelationToken) before .Select(). But doing so will also harm the performance of the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.