我有这样的东西:
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/