繁体   English   中英

如何从文本文件中读取并存储到c#中的数组列表?

[英]How to read from a text file and store to array list in c#?

我正在尝试读取文本文件并将其数据存储到数组列表中。 它没有任何错误。 我的文本文件里面是这样的。

277.18
311.13
349.23
277.18
311.13
349.23
277.18
311.13
349.23 

但在控制台输出中我可以看到这么多数据。

277.18
311.13
349.23
349.23
**329.63
329.63
293.66
293.66
261.63
293.66
329.63
349.23
392**
277.18
311.13
349.23
277.18
311.13
349.23
277.18
311.13
349.23

还有粗体数字不在我的文本文件中。 这是我的代码。 怎么解决这个? 有谁可以帮助我吗...

        OpenFileDialog txtopen = new OpenFileDialog();
        if (txtopen.ShowDialog() == DialogResult.OK)
        {
            string FileName = txtopen.FileName;
            string line;
            System.IO.StreamReader file = new System.IO.StreamReader(FileName.ToString());
            while ((line = file.ReadLine()) != null)
            {
                list.Add(double.Parse(line));
            }
            //To print the arraylist
            foreach (double s in list)
            {
                Console.WriteLine(s);
            }
        }

我认为您的list已包含一些数据,您应该在向其添加新文件数据之前将其清除。

OpenFileDialog txtopen = new OpenFileDialog();
if (txtopen.ShowDialog() == DialogResult.OK)
{
    list.Clear();   // <-- clear here

    string FileName = txtopen.FileName;
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader(FileName.ToString());
    while ((line = file.ReadLine()) != null)
    {
        list.Add(double.Parse(line));
    }
    //To print the arraylist
    foreach (double s in list)
    {
        Console.WriteLine(s);
    }
}

其他明智的事情似乎在这里很好。

尝试使用Linq ,它不会向现有列表添加任何内容:

if (txtopen.ShowDialog() == DialogResult.OK) {
  var result = File
    .ReadLines(txtopen.FileName)
    .Select(item => Double.Parse(item, CultureInfo.InvariantCulture));

  // if you need List<Double> from read values:
  //   List<Double> data = result.ToList();
  // To append existing list:
  //   list.AddRange(result);

  Console.Write(String.Join(Environment.NewLine, result));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM