Created
January 6, 2013 15:15
-
-
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>.
This file contains hidden or 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 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