Within one of my classes I have a number of methods which all have similar purposes; these methods convert different objects into valid JSON representation. Each method does slightly different things as the objects being fed into the method are different and therefore their JSON output will also be subtly different.
Within these methods a for loop exists, the purpose of this loop is to check whether or not the field being converted into JSON is the last one in the object, if it is not then a , will be placed after the converted JSON string, as is normal within JSON.
Below is an example of one of these for loops:
for (int i = 0; i < numberOfSections; i++)
{
if (i == numberOfSections - 1)
{
output += SectionToJson(root.Sections[i]);
}
else
{
output += SectionToJson(root.Sections[i]);
output += ",";
}
}
One thing to note here is that the call to the method (SectionToJson here) is different within each method. Therefore I have three different for loops doing almost the same thing but with different method calls inside their clauses.
I want to know whether or not there is a way that I can remove these ugly for loops from my three different methods and instead place their functionality inside a single method which can then be called from the three methods instead. However since the internal method call is different within each method, it makes it more difficult to place inside a single method.
I considered using the Func delegate to pass the required method through as a parameter to the new method, but this would not work as the parameters for the three internal methods are all different, and therefore I would need three different overrides of a single method. Which kinda defeats the point in removing the for loops in the first place.
Is there any other approach that I haven't considered that would help me achieve my goal here? I'm also trying to keep my list of parameters down, and would rather not go over three parameters in the new method. Preferably two.
The other two for loops in question are below.
for (int i = 0; i < numberOfQuestionsInBank; i++)
{
if (i == numberOfQuestionsInBank - 1)
{
output += QuestionPropertyToJson(questionBank.Properties[i]);
}
else
{
output += QuestionPropertyToJson(questionBank.Properties[i]);
output += ",";
}
}
for (int i = 0; i < numberOfSections; i++)
{
if (i == numberOfSections - 1)
{
requiredSections += "\"" + (i+1) + "\"";
}
else
{
requiredSections += "\"" + (i+1) + "\"";
requiredSections += ",";
}
}