Skip to content

Instantly share code, notes, and snippets.

@ti-ka
Last active August 2, 2017 05:54
Show Gist options
  • Save ti-ka/168be212b49ec67f39ee4c34b6cefbaf to your computer and use it in GitHub Desktop.
Save ti-ka/168be212b49ec67f39ee4c34b6cefbaf to your computer and use it in GitHub Desktop.
CSV to C# List of Cells
private List<Dictionary<string, object>> CSVToListOfDictionary(string csv)
{
var items = new List<Dictionary<string, object>>();
var headers = new List<object>();
var lines = csv.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line == string.Empty)
continue;
var cells = new List<object>();
var regex = new Regex("((?<=\")[^\"]*(?=\"(,|$)+)|(?<=,|^)[^,\"]*(?=,|$))");
foreach (Match m in regex.Matches(line))
{
cells.Add(m.Value.Trim());
}
if (i == 0)
{
headers = cells;
continue;
}
else
{
var dictionary = new Dictionary<string, object>();
foreach (var header in headers)
{
var columnIndex = headers.IndexOf(header);
dictionary[header.ToString()] = cells[columnIndex];
}
items.Add(dictionary);
}
}
return items;
}
private List<List<object>> CSVToCells(string csv)
{
var items = new List<List<object>>();
var lines = csv.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i].Trim();
if (line == string.Empty)
continue;
var cells = new List<object>();
var regex = new Regex("((?<=\")[^\"]*(?=\"(,|$)+)|(?<=,|^)[^,\"]*(?=,|$))");
foreach (Match m in regex.Matches(line))
{
cells.Add(m.Value.Trim());
}
items.Add(cells);
}
return items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment