0

我有一个类似的列表:

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

但我想转让为:

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

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

4

3 回答 3

1

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

    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)))
于 2013-07-31T03:01:15.777 回答
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; }
}
于 2013-07-31T03:03:20.783 回答
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;
}
于 2013-07-31T04:03:47.667 回答