user2641905
user2641905

Reputation: 75

Convert List of object into another List of object

I have a list as

class Vachel
{
int id{get;set;}
int vachelid {get;set;}
string title {get;set;}
}

List of Vachel as

id  vachelid  title
1   2         bus
1   3         truck
2   4         cycle
2   5         bike
2   5         bick

And I want to convert List<Vachel> to List<Result>

class Result
{
int id{get;set;}
string vachelid {get;set;}
string title {get;set;}
}

And the result must be as

   id   vachelid    title
    1   2,3         bus,truck
    2   4,5         cycle,bike,bick

I tried as

List<Vachel> V = getList();
List<Result> R = null;
 R = V.GroupBy(x=> new{x.vachelid})
    .Select
       (
       x=> new Result
         {
         id  =x.Key.id,
         vachelid =x.FirstOrDefault().vachelid,
         title   =x.FirstOrDefault().title
         }
       ).ToList();

Here I know I want to put something instead of .FirstOrDefault().vachelid and .FirstOrDefault().title but I don't know what to do.

Upvotes: 2

Views: 115

Answers (1)

cuongle
cuongle

Reputation: 75326

R = V.GroupBy(x => x.id)
     .Select(g => new Result(){
        id = g.Key,
        vachelid = string.Join(",", g.Select(x => x.vachelid).Distinct()),
        title = string.Join(",", g.Select(x => x.title).Distinct()),
     }).ToList();

Upvotes: 1

Related Questions