2014-10-31 39 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

相关问题