Created
October 20, 2012 15:03
-
-
Save pgrm/3923507 to your computer and use it in GitHub Desktop.
Simple CSV Loader first version
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
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
namespace SimpleCsvLoader | |
{ | |
public class CsvLoader | |
{ | |
private char _delimiter; | |
private string _fileName; | |
private StreamReader _reader; | |
private CsvLoader(char delimiter) | |
{ | |
_delimiter = delimiter; | |
} | |
public CsvLoader(string fileName, char delimiter = ',') | |
: this(delimiter) | |
{ | |
_fileName = fileName; | |
} | |
public CsvLoader(StreamReader sr, char delimiter = ',') | |
: this(delimiter) | |
{ | |
_reader = sr; | |
} | |
private StreamReader GetReader() | |
{ | |
if (_reader == null) | |
_reader = new StreamReader(_fileName); | |
return _reader; | |
} | |
private void CloseReaderIfNecessary() | |
{ | |
if (_fileName == null) | |
{ | |
_reader.Close(); | |
_reader = null; | |
} | |
} | |
public Dictionary<string, List<string>> LoadData(Predicate<string> filter = null) | |
{ | |
Dictionary<string, List<string>> ret = new Dictionary<string, List<string>>(); | |
if (filter == null) | |
filter = ((s) => true); | |
try | |
{ | |
string line; | |
string[] header = null; | |
string[] columns; | |
var sr = GetReader(); | |
while (!sr.EndOfStream) | |
{ | |
line = sr.ReadLine(); | |
columns = line.Split(_delimiter); | |
if (header == null) | |
{ | |
header = columns; | |
foreach (var item in header) | |
{ | |
ret.Add(item, new List<string>()); | |
} | |
} | |
else | |
{ | |
int i; | |
/// make sure that the index will stay within the bounds of the header and the current row | |
for (i = 0; i < columns.Length && i < header.Length; i++) | |
{ | |
ret[header[i]].Add(columns[i]); | |
} | |
/// in case some columns are missing in the current row, they will be filled up with NULL values | |
for (; i < header.Length; i++) | |
{ | |
ret[header[i]].Add(null); | |
} | |
} | |
} | |
} | |
finally | |
{ | |
CloseReaderIfNecessary(); | |
} | |
return ret; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment