Skip to content

Instantly share code, notes, and snippets.

@SMoni
Last active December 5, 2021 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SMoni/a7b8740013a031206318f3b18671ace3 to your computer and use it in GitHub Desktop.
Save SMoni/a7b8740013a031206318f3b18671ace3 to your computer and use it in GitHub Desktop.
Converts Csv with header from a TextReader
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