Last active
August 2, 2017 05:54
-
-
Save ti-ka/168be212b49ec67f39ee4c34b6cefbaf to your computer and use it in GitHub Desktop.
CSV to C# List of Cells
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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