I’m building a custom parser that should read a delimited list of data, and store the results in a class. My problem is, the program that generates the data doesn’t always include all the delimiters.
For example, if the last 3 properties have no value, it will skip the last 3 delimiters.
I was using something like this until I noticed this quirk:
var data = message.Split(delimiter);
if (data.Length < 5)
throw new Exception("Invalid message");
Id = data[0];
Property1 = data[1];
Property2 = data[2];
Property3 = data[3];
Property4 = data[4];
Of course, if the delimited string contains less than 5 elements, that creates a problem.
What’s the best way to parse a potentially bad delimited string into a class?
I don’t want to use an if statement for each property because some delimited strings contain over 50 properties.
I thought of creating an array of all the properties, and running a for-each loop on the data array, but I’m not sure the performance implications of this and would like to see if there’s a better way first.
Assuming that the properties are nullable
Instead of
nullyou can use any default value that makes sense for the properties.EDIT: