简体   繁体   中英

merge items in list from distinct value

I have the following model:

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;

    }
}

and I have a data set like this:

在此处输入图片说明

How can I use Linq to find duplicates in the first column (so for example merge Aether) and concatenate the other fields.

I would ideally like to see output like this:

在此处输入图片说明

What you want to do is to GroupBy on the key field (by your comment and model I'm assuming it is vm and then to perform an aggregation operation for the other fields. From your sample data you want to concatenate the strings:

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

As you do not have a default constructor you should:

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

You can have a look at: What's the difference between an object initializer and a constructor?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM