Josh Hilditch
Josh Hilditch

Reputation: 73

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:

enter image description here

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:

enter image description here

Upvotes: 1

Views: 116

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

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?

Upvotes: 1

Related Questions