将对象列表转换为另一个对象列表

时间:2013-08-13 08:07:01

标签: c# linq type-conversion

我有一个列表

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

Vachel列表 如

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

我想将List<Vachel>转换为List<Result>

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

结果必须是

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

我试过

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

我知道我想要放一些东西而不是.FirstOrDefault().vachelid.FirstOrDefault().title,但我不知道该怎么办。

1 个答案:

答案 0 :(得分:1)

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