2017-09-26 53 views
1

我有以下型號:合併在列表中的項目,從不同的價值

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

+0

我猜你需要看看它有.distinct功能 –

+0

我的MoreLinq包認爲linq也有明顯的差異 –

+0

.distinctBy就是我的意思。對不起,這是一個錯字 –

回答

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?

+0

看起來不錯,但這裏的代碼「組=>新serverMaster」是問我傳遞參數。我添加它們嗎? –

+1

@JoshHilditch - 哦,真的。那是因爲你沒有默認的構造函數,而是一個構造函數來獲取所有的參數。我會更新我的答案,但我建議使用對象初始化器,而不是構造函數 –

+0

「沒有任何參數對應於所需的形式參數'vm1'os serverMaster。這就是我得到的。 –