u936293
u936293

Reputation: 16264

Concatenating the values of one column into a single row

I have the result of a database query for a single user as:

Name   |  Role
Tom    |  Admin
Tom    |  Manager

I want to convert the result into an object:

{ Name = "Tom", Roles = "Admin, Manager" }

I can do it using a foreach and too many statements. How can it be done using a LINQ query?

The sample code can be:

using System;
using System.Collections.Generic;

public class Program
{   
    public static void Main()
    {
        var result = new [] { new { Name = "Tom", Role = "Admin"}, 
                              new { Name = "Tom", Role="Manager"}
                          };

        string roles = "";
        foreach (var u in result)
            roles += "," + u.Role;
        Console.WriteLine(result[0].Name + " " + roles);
    }
}

Upvotes: 0

Views: 31

Answers (1)

Selim Yildiz
Selim Yildiz

Reputation: 5370

You need to use Linq.GroupBy Name and select concatenating Roles by using String.Join:

var groupedResult = result.GroupBy(g => g.Name)
                            .Select(s => new
                            {
                                Name = s.Key,
                                Roles = String.Join(",", s.Select(i => i.Role))
                            });

It will give you a list, if you want to get first item of list you can use:

var firstItem = groupedResult.FirstOrDefault();

Upvotes: 1

Related Questions