zoukankan      html  css  js  c++  java
  • 学写了一段LINQ

    要写一段代码读入一个用空格分隔的几列的文件,程序中有多处类似的文件,所以想着有没有什么好点的办法。

    井名       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();
  • 相关阅读:
    《自我介绍》
    《结对-结对编项目作业名称-开发环境搭建过程》
    提取图形中指定颜色的所有像素_opencv/c++
    图形锐化_opencv/C++
    Opencv2.4.13 与Visual Studio2013 环境搭建配置
    C++基础——C面向过程与C++面向对象编程01_圆面积求解
    2017年2月26日
    基于GDAL的遥感影像显示(C#版)
    GDAL C# 开发环境配置
    shp文件的读取
  • 原文地址:https://www.cnblogs.com/speeding/p/3585673.html
Copyright © 2011-2022 走看看