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();
  • 相关阅读:
    记一次小程序支付开发的坑,超级坑
    springboot集成redis 附redis基本操作类
    springboot整合mybatis及封装curd操作-配置文件
    微信小程序开发
    vue各种插件
    java数据导出成 EXCEL
    jsp自定义标签
    java生成验证码
    文字对齐格式
    css阴影效果
  • 原文地址:https://www.cnblogs.com/speeding/p/3585673.html
Copyright © 2011-2022 走看看