Some background about my code, I basically have a record class which has a lot of properties to capture the required data provided in the form of .txt files and each column is divided into their own separate files i.e. Month.txt, Day.txt, containing 600 rows of data in each.
Now, I have a second array which is basically a collection of the aforementioned class and I give it max value of 600 (as there are 600 of data). This class possesses an Initialization method.
This way it Initializes my records each column at the time, but I have to know the fixed size of the rows to not run into index out of range exception. Also, I have a lot of properties so the overall "if else" statements make this code look very redundant and hard on the eye. Flexibility is also an issue as the point resets to 0, so when I want to add extra data, I will just be overriding the original 600.
Is there anyway to improve this?
The code is suboptimal, because it checks the file name for each line in that file. It is better to decide what field to set before the loop, and then use that decision throughout the loop.
First, make a look-up table of setters based on the file prefix:
var setters = new Dictionary<string,Action<Record,string>> {
["Day"] = (r,v) => r.Day = v
, ["Month"] = (r,v) => r.Month = v
, ...
};
With this look-up in place, the reading code becomes straightforward:
using (StreamReader R = new StreamReader(file.FullName)) {
var pos = File.Name.IndexOf("_");
Action<Record,string> fieldSetter;
if (pos < 0 || !setters.TryGetValue(File.Name.Substring(0, pos), out fieldSetter)) {
continue; // Go to next file
}
string temp;
while((temp = R.ReadLine()) != null) {
fieldSetter(records[pointer++], temp);
}
}
First, we look up the setter using the prefix from the file name up to the first underscore character '_'
. Then we go through the lines from the file, and call that setter for each record passing the string that we got.
Adding new fields becomes simple, too, because all you need is to add a new line to the setters
initializer.