ger
ger

Reputation: 414

How to Read a text file add line to List<> in Linq

I have this code for get a column in a text file (cvs) that I only need 2 first columns

List<string> SubStations = new List<string>();

using (StreamReader leer = new StreamReader(fs, System.Text.Encoding.Default, true))
{

    string line;
    while ((line = leer.ReadLine()) != null)
    {
        SubStations.Add(line);
    }
}

foreach (var item in SubStations)
{
    string[] StationDivision = item.Split(',');
    Console.WriteLine("Station {0}, Substation {1}",
        StationDivision[0].ToString(), 
        StationDivision[1].ToString());
}

I would like to know, if I can put the code surrounded by the foreach in the while iterator and don't use a list<>, and make it with linq?

Upvotes: 0

Views: 2248

Answers (3)

Abolfazl
Abolfazl

Reputation: 1710

If you just want to get rid of foreach,Why you don't use following code?

SubStations.Select(x=>x.Split(',')).ToList().ForEach(f=>Console.WriteLine("Station {0}, Substation {1}",
        f[0].ToString(), 
        f[1].ToString()))

Upvotes: 0

pascx64
pascx64

Reputation: 984

You can read the entire file using System.IO.File.ReadAllLines, which will return a List<string>. Then you can simply do a Select on it, split the cols and return the resulting array.

var lines = System.IO.File.ReadAllLines("file").Select(x => x.Split(',') );

foreach (var line in lines)
    Console.WriteLine($"Station {line[0]}, Substation {line[1]}");

Upvotes: 1

Magnetron
Magnetron

Reputation: 8583

Yes, you can.

Console.WriteLine(
    line.Split(',').Select(x => 
        $"Station {x[0]}, Substation {x[1]}")
    );

But as noted, you should use a Csv parser library instead.

Upvotes: 0

Related Questions