Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query to merge distinct items in a list [duplicate]

Tags:

c#

linq

I have the following model:

public class Result
{
    public int Id { get; set; }
    public string Company { get; set; }        
}

And I have a List with data similar to the following:

Id        Company
=================
21        Microsoft
22        Apple
22        IBM
23        Microsoft

How can I use Linq to give me the distinct ID's, concatenating the Company column with a delimiter?

My output should be:

Id        Company
=================
21        Microsoft
22        Apple, IBM
23        Microsoft
like image 463
Evonet Avatar asked Apr 22 '15 12:04

Evonet


1 Answers

You can use GroupBy and String.Join:

IEnumerable<Result> query = results.GroupBy(r => r.Id)
    .Select(g => new Result
    { 
        Id = g.Key, 
        Company = String.Join(", ", g.Select(r => r.Company)) 
    });
like image 77
Tim Schmelter Avatar answered Sep 20 '22 23:09

Tim Schmelter