0

I have a query in linq-to-sql as follows:

var query = (from users in _context.Users 
            join consumers in _context.Consumers 
            on users.usersId equals consumers.consumerId 

            from clients in _context.Clients.Where(x => x.Id == users.Id).DefaultIfEmpty().Take(1)
            where consumerId.Contains(consumers.consumerId)
            select new UserConsumerDto 
            {
             FirstName = users.FirstName, 
             LastName = users.LastName, 
             ClientName = clients.Name
            }).ToList()

The above query returns me several rows; meaning that a user can have multiple clients. Therefore, I added Take(1) to get only one client for the time being.

Now, when I remove the Take(1), several records are returned. I want to avoid this, by adding the client name in a single record for a user by separated comma.

For eg:

User 1 | ClientA, ClientB 

Instead of:

User 1 | Client A
User 1 | Client B

Can someone please help me to achieve this?

crazydev
  • 575
  • 2
  • 9
  • 30

2 Answers2

1

You can use group by to group the records by for example UserName and then aggregate the client names using string.Join(",",ClientName) to concatenate the client names.
Here is a sample code:

    var userClients = from c in (dbContext joined tables)
      group c by c.UserName into u 
      select new {
          UserName = u.First().UserName,
          ClientName = string.Join(",", (from n in u select n.ClientName).ToArray()) 
      };

Check the sample code in this demo

Amir Molaei
  • 3,700
  • 1
  • 17
  • 20
0

You can try this code

SELECT DISTINCT ST2.SubjectID, 
    SUBSTRING(
    (
    SELECT ','+ST1.StudentName AS [text()]
    FROM dbo.Students ST1
    WHERE ST1.SubjectID = ST2.SubjectID
    ORDER BY ST1.SubjectID
    FOR XML PATH ('')
    ), 2, 1000) [Students]
    FROM dbo.Students ST2

for reference check

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57