user3826166
user3826166

Reputation: 39

Getting Data From IEnumerable

I have text file which contains airport Codes in this format:

"AAA","","Anaa Arpt","PF","","","AAA","2","N","272"

I used a StreamReader to to read the line from file and then I add that line to string list finally I convert that list to IEnumerable type.

Can you please help me how could I get only three values from each line for example

I want to get only these three values from each row.

Please find below the code.

using (StreamReader sr = new StreamReader("C:/AirCodes/RAPT.TXT"))
{
    String line;

    while ((line = sr.ReadLine()) != null)
    {
        aircodesFromTravelPort.Add(line);
        Console.WriteLine(line);
    }
}
var codes = (IEnumerable<String>)aircodesFromTravelPort;
foreach (var aircode in codes)

Upvotes: 2

Views: 194

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

It seems that you can try using Linq, something like that:

  var codes = File
    .ReadLines(@"C:/AirCodes/RAPT.TXT")
    .Select(line => line.Split(','))
    .Select(items => new {
       // I've created a simple anonymous class, 
       // you'd probably want to create you own one
       Code = items[0].Trim('"'),    //TODO: Check numbers
       Airport = items[2].Trim('"'),
       Country = items[3].Trim('"')
    })
    .ToList();

  ...

  foreach(var item in codes) 
    Console.WriteLine(item);

Upvotes: 3

t3chb0t
t3chb0t

Reputation: 18744

I like Regex with named groups:

var line = @"""AAA"","""",""Anaa Arpt"",""PF"","""","""",""AAA"",""2"",""N"",""272""";
var pattern = @"^""(?<airportCode>\w+)"",""(\w*)"",""(?<ariportName>[\w\s]+)"",""(?<cuntryCode>\w+)""";
Match match = Regex.Match(line, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
    string airportCode = match.Groups["airportCode"].Value;
    string ariportName = match.Groups["ariportName"].Value;
    string cuntryCode = match.Groups["cuntryCode"].Value;
}

Upvotes: 0

Wet Noodles
Wet Noodles

Reputation: 805

You'll probably want to make use of String's Split function on each line to get the values into an array.

while ((line = sr.ReadLine()) != null)
{
  var values = line.Split(","); // here you have an array of strings containing the values between commas

  var airportCode = values[0];
  var airportName = values[2];
  var airportCountry = values[3]; 
  var airportInfo = airportCode + "," + airportName + "," + airportCountry;
  aircodesFromTravelPort.Add(airportInfo );
  // what you actually do with the values is up to you, I just tried to make it as close to the original as possible.

  Console.WriteLine(airportInfo);
}

Hope this helps!

Upvotes: 2

Related Questions