如何将多行分组成一行?

时间:2011-07-28 14:26:37

标签: 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'

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

3 个答案:

答案 0 :(得分: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);
        }

答案 1 :(得分:1)

如果您的类型是:

class Foo
{
   public int MyInt { get; set;}
   public string MyString { get; set; }
}

然后您的查询将是:

IEnumerable<Foo> foos = ..    
var output = foos.GroupBy(foo => foo.MyInt, foo => foo.MyString);

我假设您不需要将组内的字符串连接在一起(因为您提到了SelectMany)。

答案 2 :(得分:0)

我不知道你的对象结构是什么样的,但是下面的内容可以帮助你。

var rawData = new []
{
    new { Id = 1, Description = "test1" },
    new { Id = 1, Description = "test2" },
    new { Id = 2, Description = "test3" },
    new { Id = 2, Description = "test4" },
    new { Id = 3, Description = "test4" },
};

var result = from data in rawData
    group data by data.Id into g
select new { g.Key, Descriptions = string.Join(",", g.Select(i => i.Description)) };

result.Dump();

您可以使用LinqPad(http://www.linqpad.net)

测试这些语句