【问题标题】:Convert List of object into another List of object将对象列表转换为另一个对象列表
【发布时间】:2013-08-14 18:09:48
【问题描述】:

我有一个列表

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,但我不知道该怎么做。

【问题讨论】:

    标签: c# linq type-conversion


    【解决方案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();
    

    【讨论】:

    • @user2641905:对不起,我没关注你,你能详细说明一下吗?
    • 请您再看看问题。
    • @user2641905:我又看了一遍,但还是没明白你的意思,请问你能用体面的英文if i want uniqes vales only seperet by吗?
    • 在 List Vechle 中,对于 vecheleid = 5,有两个 Title 自行车和 bick,我希望结果为 vecheleid = 5 和 title = bike,bick 从您的代码中我得到 vechelid = 4,5,5和 Title = cycle,bike,bick 但我只想要 vechelid = 4,5 和 Title = cycle,bike,bick
    • @user2641905:知道了,我改了答案
    猜你喜欢
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2021-12-11
    • 2022-06-10
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多