Does anyone know how to convert a specific column in a csv file to string List ? I am trying to have a 'contact number' list from csv file. (Please see my csv file in below)
List<string> contactNumberList = new List<string>();
-- contactNumberList.Add("1888714"); (Manual)
---contactNumberList.Add("1888759");(Manual)
"Email","Opt In Date","Opted Out","Opt In Details","Email Type","Opted Out Date","Opt Out Details","Contact Number","Salutation"
"test1@testApp.com","05/01/2014 11:23 AM","F","User Name: capn@goldpop.org.uk. IP Address: 62.213.118.139","0","","","1888714","Mrs Hall"
"test2@testApp.com","05/01/2014 11:23 AM","F","User Name: capntransfer@goldpop.org.uk. IP Address: 62.213.118.139","0","","","1888759","Mrs Heyworth"
For parsing CSVs I suggest using a ligrary as simply splitting by line /columns separator can bring to errors if the values are escaped.
Ie
"Mr John, Bob Smith"
is a valid CSV as it is escaped with quotes. But a Split function will stop working.
One valid choice is LumenWorks (you can find it in NuGet).
Ie
using (var csv = new CsvReader(r, false, csvParserConfiguration.ColumnSeparator, '"', '"', '#', ValueTrimmingOptions.None))
{
// Read lines
while (csv.ReadNextRecord())
{
contactNumberList.Add[7];
}
}
逐行读取文件,用逗号分隔Split()
,选择所需的列,剪掉引号并添加到列表中?
Try this:
int columnId = 3;
string[] lines = File.ReadAllLines(@"C:\test.csv");
var list = lines.Select(line =>
{ var values = line.Split(';');
return values[columnId];
});
You could try the following:
var reader = new StreamReader(File.OpenRead(@"C:\test.csv"));
List<string> contactNumbersList = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
contactNumbersList.Add(values[7]);
}
but better yet you could use a dedicated library like CSV Reader .
IEnumerable<string> strings = System.IO.File.ReadAllLines({filepath})
.Select(x => x.Split(';')[{columnId}])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.