如何将多行分组成一行?

Fre*_*dou 3 c# linq-to-objects

我有这样的事情:

   int, string
   ------------
    1, 'test1'
    1, 'test2'
    2, 'test1'
    2, 'test2'
    2, 'test3'
    3, 'test1'
    4, 'test1'
    4, 'test2'
Run Code Online (Sandbox Code Playgroud)

我想将其转化为

   int, string
   ------------
    1, 'test1, test2'
    2, 'test1, test2, test3'
    3, 'test1'
    4, 'test1, test2'
Run Code Online (Sandbox Code Playgroud)

我尝试过很多东西,比如GroupMy和SelectMany,但它给了我运行时错误

Jay*_*Jay 5

这对我有用:

var list = new List<KeyValuePair<int, string>>() {
           new KeyValuePair<int, string>(1, "test1"),
           new KeyValuePair<int, string>(1, "test2"),
           new KeyValuePair<int, string>(2, "test1"),
           new KeyValuePair<int, string>(2, "test2"),
           new KeyValuePair<int, string>(2, "test3"),
           new KeyValuePair<int, string>(3, "test1"),
           new KeyValuePair<int, string>(4, "test1"),
           new KeyValuePair<int, string>(4, "test2"),
        };

        var result = (from i in list
                      group i by i.Key into g
                      select new
                      {
                          Key = g.Key,
                          Values = string.Join(", ", (from k in g
                                                      select k.Value))
                      });

        foreach (var x in result)
        {
            Console.WriteLine(x.Key + " - " + x.Values);
        }
Run Code Online (Sandbox Code Playgroud)