正在逐行读取制表符分隔的txt文件到字符串列表中。目的是使用字符串的格式类型处理字符串的每个单词,如datetime或float或字符串等?这样就可以绘制数据。还有其他有效的方法吗?
using (StreamReader file = new StreamReader(@"C:\Users\\Desktop\snpprivatesellerlist.txt"))
{
while ((line = file.ReadLine()) != null)
{
char[] delimiters = new char[] { '\n' };
string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
st = parts[i];
// process the line - if part[i] is date time - do something ()
// if part[i] is a float - do something else()
}
}
}
感谢任何帮助和见解。 感谢。
答案 0 :(得分:2)
我建议使用TryParse,就像这样...
string line;
using (StreamReader file = new StreamReader(@"C:\Users\Desktop\snpprivatesellerlist.txt"))
{
while ((line = file.ReadLine()) != null)
{
string st;
DateTime dtPart;
float flPart;
char[] delimiters = new char[] { '\n' };
string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
st = parts[i];
if (DateTime.TryParse(st, out dtPart))//Is of type DateTime
{
//Do something with DateTime dtPart
}
else if (float.TryParse(st, out flPart))//Is of type float
{
//Do something with float flPart
}
else//Can be considered a string
{
//Do something with string st
}
}
}
}
答案 1 :(得分:0)
然后,您可以创建一个结构类来存储每个行值。
class LineData
{
public float a {get; set;}
public DateTime b {get; set;}
}
在方法实现中(即在while
中):
string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
//You know 1st column is float, 2nd column is datetime
var dt = new LineData();
float.TryParse(parts[0], out dt.a);
DateTime.TryParse(parts[1], out dt.b);
//...
//store dt in a list/array. (not shown here)
答案 2 :(得分:0)
有点解决我的问题的代码 - 但我仍然在努力。
using (StreamReader file = new StreamReader(@"C:\Users\Desktop\snpprivatesellerlist.txt"))
{
while ((line = file.ReadLine()) != null)
{
char[] delimiter1 = new char[] { '\n' };
string[] part1 = line.Split(delimiter1, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < part1.Length; i++)
{
sepList.Add(part1[i]);
//st = part1[i];
}
}
file.Close();
}
char[] delimiter2 = new char[] { '\t' };
for (int j = 4; j < sepList.Count; j++)
{
st = sepList[j];
string[] part2 = st.Split(delimiter2, StringSplitOptions.RemoveEmptyEntries);
alist.Add(part2);
}
//DateTime time = new DateTime();
//float value = new float();
string tagname = alist[0][0];
for (int y = 0; y < alist.Count; y++)
{
if (alist[y][0]==tagname)
{
alist1.Add(alist[y]);
}
else
{
SensorProbeDataContainer sensorprobe = new SensorProbeDataContainer();
sensorprobe.Setdata(templist);
sensorprobe.SensorProbe = sensorprobe.data[0][0];
ProbeList.Add(sensorprobe.SensorProbe);
DateTime.TryParse(sensorprobe.data[0][2], out sensorprobe.StartDate);
DateTime.TryParse(sensorprobe.data[(sensorprobe.data.Count - 1)][2], out sensorprobe.EndDate);
classcontainer.Add(sensorprobe);
tagname = alist[y][0];
templist.Clear(); }
}
我试图在这个帖子上关注它 - https://stackoverflow.com/questions/10719396/iterating-separating-list-of-string-arrays-based-on-first-element
谢谢大家的帮助。如果发现代码中的任何错误,请指出。