Skip to content

Instantly share code, notes, and snippets.

@pgrm
Created October 20, 2012 15:03
Show Gist options
  • Save pgrm/3923507 to your computer and use it in GitHub Desktop.
Save pgrm/3923507 to your computer and use it in GitHub Desktop.
Simple CSV Loader first version
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