我有一个文本文件,如" ddd,aaa,bb,cccc,3"。这个文字有一百万行。我把所有的字都放在数组中。例如
value1=ddd, value2=aaa , value3=bbb , value4=cccc, value5=3`.
它应该是不同的算法,但这并不重要。
当读取此文本时,它取最后一个数字3
并重复第一个记录三次,因为最后一个数字是3.如果最后一个数字应该是4,那么它将重复四次。它给出了新的行号
1,aa,bb,ccc,ddd,3
2,aa,bb,ccc,ddd,3
3,aa,bb,ccc,ddd,3
现在我想要,当这个行数等于10000时,它必须写新文本。例如,如果我的阅读文本有50000条记录,则必须写入5.文本文件。我怎样才能做到这一点。你能帮帮我吗?
这是写方法。
public void Save()
{
value1.Remove("SE");
value2.Remove("CS");
value3.Remove("NAME");
value4.Remove("SURNAME");
value5.Remove("Number");
int rowNum = 1;
int maxNum = 1000;
String aa = "";
String TMPvalue;
for (int d = 0; d < value5.Count; d++)
{
for (int m = 0; m < (Int32)value5[d]; m++,rowNum++)
{
TMPvalue = rowNum + "," + value1[d] + "," + value2[d] + "," + value3[d] + "," + value4[d] + "," + "TEB";
aa = aa + TMPvalue + "\n";
if(rowNum==maxNum){
path = path + Convert.ToString(xnum) + ".txt";
file1 = new System.IO.StreamWriter(path);
aa = "ROWNUM,v1,v2,v3,v4" + "\n\r" + aa;
string[] lines = aa.Split('\n');
foreach (string s in lines)
{
file1.WriteLine(s);
}
file1.close();
rowNum=1;
aa = "";
}
}
}
file2 = new System.IO.StreamWriter(path);
aa = "ROWNUM,v1,v2,v3,v4" + "\n\r" + aa;
string[] lines = aa.Split('\n');
foreach (string s in lines)
{
file2.WriteLine(s);
}
file2.close()
}
答案 0 :(得分:0)
您可以使用以下LINQ查询,该查询可以执行您想要的操作:
var lines10kGroups = File.ReadLines(@"C:\Temp\File.txt")
.Select(l => new { Line = l, Fields = l.Split(',') })
.Where(x => x.Fields.Length > 1)
.Select(x => new{ LastToken = x.Fields.Last().Trim().Split('=').Last(), x.Fields, x.Line})
.Where(x => x.LastToken.All(Char.IsDigit)) // checks if all characters are digits, pre-check for int.Parse
.Select(x => new { Count = int.Parse(x.LastToken), x.Line, x.Fields })
.SelectMany(x => Enumerable.Repeat(x.Line, x.Count)) // this repeats count-lines
.Select((line, index) => new{ line, index })
.GroupBy(x => x.index / 10000); // integer division trick to group by 10k lines
string targetDir = @"C:\Temp\TestDirectory";
Directory.CreateDirectory(targetDir);
int fileNum = 0;
foreach (var lineGroup in lines10kGroups)
{
string path = Path.Combine(targetDir, string.Format("File_{0}.txt", ++fileNum));
while(File.Exists(path))
path = Path.Combine(targetDir, string.Format("File_{0}.txt", ++fileNum));
File.WriteAllLines(path, lineGroup.Select(x => x.line));
}