我有一个List<string>
,如下所示:
List<string> source = new List<string>() {
"Test;12345",
"Test;6789",
"Test;101112",
"Demo;1",
"Demo;2",
};
我需要将此压缩为新的List<string>
:
{
"Test;12345;6789;101112",
"Demo;1;2"
}
此致
答案 0 :(得分:2)
根据您对我的评论的回答
预期结果将是字符串列表:Demo; 1和 测试; 12345; 6789; 101112
您正在寻找 Linq GroupBy
,例如
using System.Linq;
...
List<string> source = new List<string>() {
"Test;12345",
"Test;6789",
"Test;101112",
"Demo;1",
"Demo;2",
};
List<string> result = source
.Select(line => line.Split(new char[] {';'}, 2))
.GroupBy(line => line[0], line => line[1])
.Select(group => $"{group.Key};{string.Join(";", group)}")
.ToList();
让我们看看:
Console.Write(string.Join(Environment.NewLine, result));
结果:
Test;12345;6789;101112
Demo;1;2
答案 1 :(得分:0)
您可以尝试以下代码,
var result = source.ToLookup(x => x.Split(";")[0], x=>x.Split(";")[1]).Select(x => string.Concat(x.Key,";",string.Join(";",x))).ToList();