sushi
sushi

Reputation: 157

How to get all rows for specific column from .csv file

In my project, I have a .csv file with many columns. I need to extract all rows for only first column. I've managed to read all lines, but got stuck on how to extract rows from first column to another .csv file.

string filePath = @"C:\Users\BP185150\Desktop\OTC.csv";
            
string[] OTC_Output = File.ReadAllLines(@"C:\Users\BP185150\Desktop\OTC.csv");

foreach (string line in OTC_Output)
{
     Console.WriteLine(line);
     Console.Read();
}
Console.ReadLine();

Upvotes: 0

Views: 1937

Answers (3)

Manuel Fabbri
Manuel Fabbri

Reputation: 568

In lineItems, you'll have all the columns splitted:

var lineItems = line.Split(";").ToArray();

Then, parse the value only for the first of them:

lineItems.GetValue(0).ToString();

Upvotes: 1

MarekK
MarekK

Reputation: 438

Well if you want to use File.ReadAllLines, the best way to get the first column is to split the line with a delimiter that your csv is using. Then just add the first item of every line to a collection.

var column = OTC_Output.Select(line => line.Split(';').First()).ToList();

Upvotes: 1

Willie
Willie

Reputation: 382

Depending on what seperator your csv is using you can use the string.split() function.

e.g.

string firstItem = line.Split(',')[0];
Console.WriteLine(firstItem);

Adding them to a collection:

ICollection<string> firstItems = new List<string>();
string[] OTC_Output = File.ReadAllLines(@"C:\Users\BP185150\Desktop\OTC.csv");

foreach (string line in OTC_Output)
{
    firstItems.Add(line.Split(',')[0]);
}

Upvotes: 1

Related Questions