要写一段代码读入一个用空格分隔的几列的文件,程序中有多处类似的文件,所以想着有没有什么好点的办法。
井名 X坐标 Y坐标 深度
测试井1 634600 4116000 3456
井2 640000 4200000 3333
以前没学过LINQ,只知道它应该能够方便地读入这类数据,google了一阵,终于写出来了。
var query = from line in File.ReadAllLines(wellListFile, Encoding.GetEncoding("GBK")) .Skip(1) //第一行要略过 let fields = line.Split(new char[] { ' ', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries) select new Well { Name = fields[0], X = double.Parse(fields[1]), Y = double.Parse(fields[2]), Depth = double.Parse(fields[3]) }; return query.ToArray<Well>();
而以前的代码是这样的:
<Well> wells = new List<Well>(); try { using (StreamReader r = new StreamReader(wellListFile)) { string line; while ((line = r.ReadLine()) != null) { string[] fields = line.Split(new char[] { ' ', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); if (fields.Length < 4) continue; string name = fields[0]; double x, y, depth; if (!double.TryParse(fields[1], out x)) continue; if (!double.TryParse(fields[2], out y)) continue; if (!double.TryParse(fields[3], out depth)) continue; Well well = new Well(name, x, y, depth); wells.Add(well); } } } catch (Exception) { //错误的行一概略过,第一行自然也略过了 } return wells.ToArray();