0

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);
    }
}

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

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.