I would like to read in a CSV into a dictionary, however most examples I see have the first column as keys. I would like the field names to be keys.
CSV File:
Name,Type,Classification
file1.txt,text,Secondary
file2.txt,text,Primary
Output dictionary (what I would like):
dict = {
Name: [file1.txt, file2.txt],
Type: [text, text],
Classification: [Secondary, Primary]
}
I'm not sure if I can extend this somehow:
private void LoadCSV()
{
var mydict = new Dictionary<string, List<string>>();
var lines = File.ReadAllLines(@"C:\test.csv");
string[] columnHeaders = lines[0].Split(',');
foreach (string columnHeader in columnHeaders)
{
mydict[columnHeader] = new List<string>();
}
}
Edit:
This may be doing what I want, but perhaps not very efficient:
private void LoadCSV()
{
var mydict = new Dictionary<string, List<string>>();
var lines = File.ReadAllLines(@"C:\test.csv");
string[] columnHeaders = lines[0].Split(',');
string[] allLines = lines.Skip(1).ToArray();
int count = 0;
foreach (string headerPart in columnHeaders)
{
var valuelist = new List<string>();
foreach (string line in allLines)
{
List<string> l = line.Split(',').ToList();
var element = l.ElementAt(count);
valuelist.Add(element);
}
mydict[headerPart] = valuelist;
count++;
}
}