Last active
December 5, 2021 12:22
-
-
Save SMoni/a7b8740013a031206318f3b18671ace3 to your computer and use it in GitHub Desktop.
Converts Csv with header from a TextReader
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
public static class ReadFromCsv { | |
public static IEnumerable<IDictionary> asKeyValuePairs(this TextReader Reader_, string Delimiter_ = ";") { | |
var splitThis = Delimiter_.asSplitter(); | |
var result = new List<Dictionary<string, object>>(); | |
var columns = splitThis(Reader_.ReadLine()); | |
string line; | |
while ((line = Reader_.ReadLine()) != null) { | |
if (line == string.Empty) | |
continue; | |
splitThis(line) | |
.asRowWith(columns) | |
.addTo(result); | |
} | |
return result; | |
} | |
private static Func<string, string[]> asSplitter(this string Delimiter_) { | |
var separator = new[] { Delimiter_ }; | |
return Data_ => Data_.Split(separator, StringSplitOptions.None); | |
} | |
private static Dictionary<string, object> asRowWith(this IReadOnlyList<string> Entries_, IReadOnlyList<string> Columns_) { | |
var row = new Dictionary<string, object>(); | |
for (var columnIndex = 0; columnIndex < Entries_.Count; columnIndex++) { | |
row.Add(Columns_[columnIndex], Entries_[columnIndex]); | |
} | |
return row; | |
} | |
private static void addTo(this IEnumerable Row_, IList ToThis_) { | |
ToThis_.Add(Row_); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment