c# - 如何将多行分组为一行?

标签 c# linq-to-objects

我有这样的东西:

   int, string
   ------------
    1, 'test1'
    1, 'test2'
    2, 'test1'
    2, 'test2'
    2, 'test3'
    3, 'test1'
    4, 'test1'
    4, 'test2'

我想把它变成

   int, string
   ------------
    1, 'test1, test2'
    2, 'test1, test2, test3'
    3, 'test1'
    4, 'test1, test2'

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

最佳答案

这对我有用:

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);
        }

关于c# - 如何将多行分组为一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6860590/

相关文章:

c# - 使用 Linq 从列表中删除

c# - 这两种事务处理方式有什么区别

c# - .NET JIT 如何优化生成的代码布局?

c# - 真正的 MVVM 和第三方控件

c# - 如何使用 LINQ 或响应式(Reactive)扩展拆分带有嵌入转换标记的列表?

c# - 使用 Linq 从数据表中获取不同的行(与多列不同)

c# - 哎呀,这个作业里发生了什么

c# - 如何让 Metro GridView 中的组使用不同的布局?

c# - 使用 LINQ 过滤列表

c# - 检查列表中的所有项目是否相同