2014-10-31 70 views
-1

LINQ新手問題。將對象列表中的字段組合成一個CSV

我想將字段組合成逗號分隔的列表,當其他人在對象列表中相同時。不知道我是否正確地提出了問題。

class A 
{ 
    int id; 
    int roll; 
    string name; 

    public A(int id, int roll, string name) 
    { 
     this.id = id; 
     this.roll = roll; 
     this.name = name; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<A> aList = new List<A>(); 
     A a1 = new A(24, 501, "alex"); 
     A a2 = new A(12, 27, "steven"); 
     A a3 = new A(24, 67, "bob"); 
     A a4 = new A(1, 90, "erin"); 
     A a5 = new A(12, 27, "christy"); 
     aList.Add(a1); 
     aList.Add(a2); 
     aList.Add(a3); 
     aList.Add(a4); 
     aList.Add(a5); 

    } 

由於A2和A5相同(12,27),創建對象的一個​​新的列表時,我想有它的領域之一爲(12,27日,「史蒂芬,克里斯蒂ID和滾動「),因爲沒有任何匹配而休息。

如果問題/解釋混亂,我很抱歉。

+0

在「A」類中,您只有字段沒有屬性:P – py3r3str 2014-10-31 17:36:23

+1

您堅持實施「A」的實現嗎?這聽起來像'名稱'應該是'名單名稱',因爲你可以有多個 – 2014-10-31 17:42:14

+0

@ py3r3str糟糕!編輯它:) – 2014-10-31 17:50:27

回答

4
var res = aList 
    .GroupBy(z => new { z.id, z.roll }) 
    .Select(z => new A(z.Key.id, z.Key.roll, string.Join(",", z.Select(z2 => z2.name)))) 
    .ToList(); 

請注意idrollname將不得不public

相關問題