是否存在与VB6中的TextFieldParser
类等效的现代.NET?性能远低于简单的String.Split()
答案 0 :(得分:1)
我已将效果与该代码进行了比较:https://gist.github.com/Ruszrok/7861319
我使用了一个输入文件,其中大约有1 000 000条记录用空格分隔。我尝试了五次实验。
String.Split
平均时间: 291 ms Microsoft.VisualBasic.FileIO.TextFieldParser
平均时间: 15843 ms 您可以使用Microsoft.VisualBasic.FileIO.TextFieldParser
课程。参考Microsoft.VisualBasic
。主旨中的样本。
答案 1 :(得分:0)
这是我的解决方案:
public class TextFieldParser
{
enum FieldType { FixedWidth, Delimited };
public enum CompleteElements
{
/// <summary>
/// Returns as many elements as fileWidths input be
/// </summary>
AllElements,
/// <summary>
/// Only returns elements who have not null values
/// </summary>
OnlyValues
};
int[] m_fieldWidths;
string m_line;
List<string> m_results;
int m_lineWidth;
public CompleteElements m_CompleteElements;
public TextFieldParser(string line)
{
m_line = line;
m_lineWidth = m_line.Length;
m_results = new List<string>();
m_CompleteElements = CompleteElements.OnlyValues;
}
public void SetCompleteElements(CompleteElements value)
{
m_CompleteElements = value;
}
public void SetFieldWidths(params int[] fileWidths)
{
m_fieldWidths = fileWidths;
}
public string[] ReadFields()
{
int pivot = 0;
m_results = new List<string>();
for (int x = 0; x < m_fieldWidths.Length; x++)
{
if(pivot + m_fieldWidths[x] <= m_lineWidth)
{
m_results.Add(m_line.Substring(pivot, m_fieldWidths[x]));
}
else
{
if (m_CompleteElements == CompleteElements.AllElements)
{
m_results.Add(null);
}
break;
}
pivot += m_fieldWidths[x];
}
return m_results.ToArray();
}
}
一个简单的会话:
string line = "1234567890123456789012345678890";
TextFieldParser parser = new TextFieldParser(line);
parser.SetFieldWidths(1, 2, 3, 4, 5, 6, 7, 8);
string[] resultOnlyValues = parser.ReadFields();
/*
results:
resultOnlyValues[0] : "1"
resultOnlyValues[1] : "23"
resultOnlyValues[2] : "456"
resultOnlyValues[3] : "7890"
resultOnlyValues[4] : "12345"
resultOnlyValues[5] : "678901"
resultOnlyValues[6] : "2345678"
*/
parser.SetCompleteElements(TextFieldParser.CompleteElements.AllElements);
string[] resultAllElement = parser.ReadFields();
/*
results:
resultAllElement[0] : "1"
resultAllElement[1] : "23"
resultAllElement[2] : "456"
resultAllElement[3] : "7890"
resultAllElement[4] : "12345"
resultAllElement[5] : "678901"
resultAllElement[6] : "2345678"
resultAllElement[7] : null
*/