如果第一个字段相同,我很难在逗号分隔的文本文件中组合一些行。这是我的档案:
Area 1 Chiller Grids aB aN and a1 a6,test,1,Ground Floor Framing
Area 1 Chiller Grids aB aN and a1 a6,test,2,Monorails West
Area 1 Chiller Grids aB aN and a1 a6,test,6,Roof Framing West
Area 1 Chiller Grids aB aN and a1 a6,test,11,Bullnose West
Area 2 Office Grids aN zA and a1 a6,101806,3,First Floor Framing East
Area 2 Office Grids aN zA and a1 a6,101806,5,Mezz Floor Framing
Area 2 Office Grids aN zA and a1 a6,101806,7,Roof Framing East
Area 2 Office Grids aN zA and a1 a6,101806,9,First Floor Ceiling
Area 3 Bridge Grids yA yE and a1 10x,101807,4,Link Floor Framing
Area 3 Bridge Grids yA yE and a1 10x,101807,8,Link Roof Framing
Area 3 Bridge Grids yA yE and a1 10x,101807,10,Bridge Catwalks
Area 3 Bridge Grids yA yE and a1 10x,101807,13,Stair 1
我需要输出为:
Area 1 Chiller Grids aB aN and a1 a6,test,1-2-6-11,Ground Floor Framing-Monorails West-Roof Framing West-Bullnose West
Area 2 Office Grids aN zA and a1 a6,101806,3-5-7-9,First Floor Framing East-Mezz Floor Framing-Roof Framing East-First Floor Ceiling
Area 3 Bridge Grids yA yE and a1 10x,101807,4-8-10-13,Link Floor Framing-Link Roof Framing-Bridge Catwalks-Stair 1
我该如何解决这个问题? 我已经尝试了一些我在这里找到的linq代码,但它并没有得到我想要的东西,我不知道该怎么做:
var a = System.IO.File.ReadAllLines(@"X:\Steelcad_Project_Files\" + dir + "\\manager1.txt");
var b = System.IO.File.ReadAllLines(@"X:\Steelcad_Project_Files\" + dir + "\\manager.txt");
var query =
from bline in b
let parts = bline.Split(',')
group parts[2] by parts[0] into bg
join aline in a on bg.Key equals aline
select aline + "," + string.Join("-", bg.ToArray());
System.IO.File.WriteAllLines(@"X:\Steelcad_Project_Files\" + dir + "\\result.txt", query.ToArray());
其中manager1文件中只包含第一个字段,如下所示:
Area 1 Chiller Grids aB aN and a1 a6
Area 2 Office Grids aN zA and a1 a6
Area 3 Bridge Grids yA yE and a1 10x
如果可能的话,我想只使用1个文件。 任何帮助将非常感激。感谢
编辑:是否可以根据第0行和第2行对行进行排序?如果它是1-11-15-2-6可以重新排列到1-2-6-11-15但是将所有区域1保持在一起等吗?
答案 0 :(得分:3)
var output = File.ReadAllLines(@"D:\\manager.txt")
.Select(line => line.Split(','))
.GroupBy(line => line[0] + "," + line[1])
.Select(group =>
group.Key + "," +
String.Join("-", group.Select(line => line[2]).ToArray()) + "," +
String.Join("-", group.Select(line => line[3]).ToArray())
);
答案 1 :(得分:0)
试试这个
var results = from l in File.ReadAllLines(@"..\..\TextFile1.txt")
let fields = l.Split(new[] { ',' })
group fields by fields[0] into g
select (g.Key + "," +
String.Join("-", g.Select(l => l[2]).ToArray()) +
"," +
String.Join("-", g.Select(l => l[3]).ToArray()));