Reputation:
I have a small text file, containing a few integers on separate lines.
I wrote the following program (just a function called ReadFromFile
) in order to read in the integers and assign them to some variables.
I wonder if I could improve it, and how? I tried reading in integers, but realized I would get errors with StreamReader
, so I carried on using strings.
Is there anyway I could improve this program?
All it does is read in the following numbers, assign the first two to two variables, and put the rest in a list.
3
4
8
8
8
8
8
8
So, I will have: var1 = 3
, var2 = 4
, myList = [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();
}
}
}
Upvotes: 2
Views: 547
Reputation: 1686
You could write it as follow :
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] );
}
}
Upvotes: 2
Reputation: 1064114
var vals = File.ReadAllLines(path).Select(int.Parse).ToList();
You might need a Skip(...)
if you have header lines; for example to match your for(int i = 2; ...)
:
var vals = File.ReadAllLines(path).Skip(2).Select(int.Parse).ToList();
Upvotes: 2