Daniel Fisher (lennybacon.com)

SOA, DATA & THE WEB

More comfort reading values from lines in CSV-files

Today I had to read values from multiple CVS-files. I wanted to build a testable and reusable solution instead of the ugly sequential spaghetti that easily happens.

So here is a sample of a line:

1 var lineReadFromCsv = 2 "42;Daniel;Fisher;1980-03-25;{79704C0D-1A4F-4DDD-80F6-CA79E81BF7CD}";

To increase the readability I created enumerations that point to the index of the position of the values in each line that I wanted to read:

1 public enum DataFormatField 2 { 3 Id = 0, 4 GivenName = 1, 5 Surname = 2, 6 DateOfBirth = 3, 7 UniqueId = 4, 8 }

I created a class called ParserParameter that contains enums that

1 public class ParserParameter 2 { 3 prop Enum FirstName { get; set; } 4 //... 5 } 6

Last but not least an extension class the provides a generic method TryGetValueOrDefault<T>(). It takes an enum member as parameter. It can convert int, long, float, decimal, double, guid, datetime as well as string and can easily be extended.

1 int id; 2 if (fields.TryGetValueOrDefault( 3 DataFormatField.Id, 4 out id)) 5 { 6 Console.WriteLine(id); 7 } 8 9 string givenName; 10 if (fields.TryGetValueOrDefault( 11 DataFormatField.GivenName, 12 out givenName)) 13 { 14 Console.WriteLine(givenName); 15 } 16

The complete code can be downloaded at forkcan.

Comments

Write a comment