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();
  • 相关阅读:
    C++中整型变量的存储大小和范围
    A1038 Recover the Smallest Number (30 分)
    A1067 Sort with Swap(0, i) (25 分)
    A1037 Magic Coupon (25 分)
    A1033 To Fill or Not to Fill (25 分)
    A1070 Mooncake (25 分)
    js 获取控件
    C#代码对SQL数据库添加表或者视图
    JS 动态操作表格
    jQuery取得下拉框选择的文本与值
  • 原文地址:https://www.cnblogs.com/speeding/p/3585673.html
Copyright © 2011-2022 走看看