从不同的值合并列表中的项目

时间:2017-09-26 05:09:54

标签: c# linq

我有以下型号:

class serverMaster
{
    public string vm { get; set; }
    public string bm { get; set; }
    public string incrday { get; set; }
    public string incrtime { get; set; }
    public string fullday { get; set; }
    public string fulltime { get; set; }
    public string backupgroup { get; set; }
    public serverMaster(string vm1, string bm1, string incrday1, string incrtime1, string fullday1, string fulltime1, string backupgroup1)
    {
        vm = vm1;
        bm = bm1;
        incrday = incrday1;
        incrtime = incrtime1;
        fullday = fullday1;
        fulltime = fulltime1;
        backupgroup = backupgroup1;

    }
}

我有这样的数据集:

enter image description here

如何使用Linq在第一列中查找重复项(例如合并Aether)并连接其他字段。

我希望看到这样的输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

您要做的是在关键字段上GroupBy(通过您的评论和模型,我假设它是vm,然后对其他字段执行聚合操作。要连接字符串的示例数据:

var result = allItems.GroupBy(item => item.vm)
                     .Select(group => new serverMaster {
                         vm = group.Key,
                         incrday = string.Join(", ", group.Select(i => i.incrday)),
                         incrtime = string.Join(", ", group.Select(i => i.incrtime)),
                         fullday = string.Join(", ", group.Select(i => i.fullday)),
                         fulltime = string.Join(", ", group.Select(i => i.fulltime)),
                         backupgroup = string.Join(", ", group.Select(i => i.backupgroup))
                     }).ToList();

由于您没有默认构造函数,您应该:

var result = allItems.GroupBy(item => item.vm)
                     .Select(group => new serverMaster (
                         group.Key,
                         string.Join(", ", group.Select(i => i.incrday)),
                         string.Join(", ", group.Select(i => i.incrtime)),
                         string.Join(", ", group.Select(i => i.fullday)),
                         string.Join(", ", group.Select(i => i.fulltime)),
                         string.Join(", ", group.Select(i => i.backupgroup))
                     )).ToList();

您可以查看:What's the difference between an object initializer and a constructor?