从文本文件中读取整数并将它们存储在列表中

时间:2016-08-25 11:41:27

标签: c#

我有一个小文本文件,在不同的行上包含几个整数。

我编写了以下程序(只是一个名为ReadFromFile的函数),以便读取整数并将它们分配给某些变量。

我想知道我是否可以改善它,以及如何?我尝试读取整数,但意识到我会因StreamReader而出错,所以我继续使用字符串。

无论如何我可以改进这个程序吗?

所有内容都按以下数字读取,将前两个变量分配给两个变量,并将其余变量放在一个列表中。

3
4
8
8
8
8
8
8

所以,我会:var1 = 3var2 = 4myList = [8,8,8,8,8,8]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;    


namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {    
            // Read the specifications from the file.
            ReadFromFile();

            // Prevent the console window from closing.
            Console.ReadLine();
        }


        /// The function that reads the input specifications from a file.
        public static void ReadFromFile()
        {
            string localPath = @"C:\Desktop\input.txt";
            StreamReader sr = new StreamReader(localPath);

            // Read all the lines from the file into a list,
            // where each list element is one line.

            // Each line in the file.
            string line = null;

            // All lines of the file.
            List<string> lines = new List<string>();

            while ( ( line = sr.ReadLine() ) != null )
            {
                lines.Add(line);
                Console.WriteLine(line);
            }          

            // Display the extracted parameters.                
            Console.WriteLine( lines[0] + " var1");
            Console.WriteLine( lines[1] + " var2");

            // Put the rest in a separate list.
            List<int> myList = new List<int>();

            for (int i = 2; i < lines.Count; i++)
            {
                Console.WriteLine("item {0} = {1}", i-1, lines[i] );
                myList.Add( Int32.Parse( lines[i] ) );
            }

            sr.Close();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

var vals = File.ReadAllLines(path).Select(int.Parse).ToList();

如果您有标题行,则可能需要Skip(...);例如,匹配您的for(int i = 2; ...)

var vals = File.ReadAllLines(path).Skip(2).Select(int.Parse).ToList();

答案 1 :(得分:3)

您可以按照以下方式编写:

public static void ReadFromFile(string localPath) // paremetrizing the path for more flexibility
    {
        StreamReader sr = new StreamReader(localPath);

        // extrating the lines from the file
        List<int> lines = Regex.Split(sr.ReadToEnd(), "\r\n").Select(int.Parse).ToList();

        // we can close the reader as we don't need it anymore
        sr.Close();

        Console.WriteLine( lines[0] + " var1");
        Console.WriteLine( lines[1] + " var2");

        // removing the first 2 elements
        lines = lines.Skip(2).ToList();



        for (int i = 0; i < lines.Count; i++)
        {
            Console.WriteLine("item {0} = {1}", i-1, lines[i] );
        }

    }