Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created January 6, 2013 15:15
Show Gist options
  • Save riyadparvez/4467864 to your computer and use it in GitHub Desktop.
Save riyadparvez/4467864 to your computer and use it in GitHub Desktop.
A csv reader class which reutrns CSV rows as List<List<string>>. So every row is a List<string>.
public class CSVReader : IEnumerable<List<string>>
{
private readonly string filePath;
private List<string> lines;
private List<List<string>> tokens;
private List<string> headers;
public string FilePath
{
get { return filePath; }
}
public IList<string> Header
{
get { return headers.AsReadOnly(); }
}
public IList<string> AllRows
{
get { return lines.AsReadOnly(); }
}
public IList<List<string>> DataRows
{
get { return tokens.AsReadOnly(); }
}
private CSVReader(string filePath)
{
this.filePath = filePath;
}
private void Read()
{
lines = File.ReadAllLines(filePath).ToList();
headers = lines
.Take(1)
.Single()
.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries)
.ToList();
tokens = lines
.Select(l => l.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries)
.ToList())
.ToList();
}
public IEnumerator GetEnumerator()
{
return tokens.GetEnumerator();
}
IEnumerator<List<string>> IEnumerable<string>.GetEnumerator()
{
return tokens.GetEnumerator();
}
public static class Builder
{
public static CSVReader CreateInstance(string filePath)
{
if(!File.Exists(filePath))
{
throw new ArgumentException();
}
CSVReader reader = new CSVReader(filePath);
reader.Read();
return reader;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment