使用LINQ - Concat重复列

时间:2013-07-31 02:50:30

标签: linq

我有一个列表:

ColumnA | ColumnB | ColumnC
--------+---------+---------
111     | 222     | xx
111     | 222     | yy
111     | 222     | zz

但我想转发为:

ColumnA | ColumnB | ColumnC
--------+---------+---------
111     | 222     | xx, yy, zz

如果可能的话,我想在同一个列表中创建更多列表来使用LINQ来实现结果。有谁知道如何做到这一点?

3 个答案:

答案 0 :(得分:1)

VB版,(使用Tuple,因为我不知道你的对象定义):

    Dim list = New List(Of Tuple(Of Integer, Integer, String))

    list.Add(Tuple.Create(111, 222, "xx"))
    list.Add(Tuple.Create(111, 222, "yy"))
    list.Add(Tuple.Create(111, 222, "zz"))

    Dim result = list.GroupBy(Function(n) Tuple.Create(n.Item1, n.Item2)) _
        .Select(Function(m) Tuple.Create(m.Key.Item1, m.Key.Item2, m.Select(Function(t) t.Item3).Aggregate(Function(x, y) x & "," & y)))

答案 1 :(得分:1)

不确定为什么要在同一个列表中查找...但这里是LINQ查询;

List<Column> list = new List<Column>();

var newList = list.GroupBy(x => new { A = x.ColumnA, B = x.ColumnB })
            .Select(y => new Column
            {
                ColumnA = y.Key.A,
                ColumnB = y.Key.B,
                ColumnC = y.ToList().Select(el => el.ColumnC).Aggregate((y1, y2) => y1 + "," + y2)
            });



class Column
{
    public string ColumnA { get; set; }
    public string ColumnB { get; set; }
    public string ColumnC { get; set; }
}

答案 2 :(得分:0)

class Program
{
    static void Main(string[] args)
    {
        List<Columns> list = new List<Columns>() {new Columns(){Column1="111",Column2="222",Column3="xx"},
        new Columns(){Column1="111",Column2="222",Column3="yy"},
        new Columns(){Column1="111",Column2="222",Column3="zz"}
        };
        var result=list.GroupBy(c=>new { c.Column1, c.Column2 })
            .Select(g=>new Columns(){Column1=g.Key.Column1,Column2=g.Key.Column2,Column3=string.Join(",",g.Select(s=>s.Column3))});
    }
}

public class Columns
{
    public string Column1;
    public string Column2;
    public string Column3;
}