I have the following code that is used for producing data for a jquery graph. However it is quite repetitive and in order to keep DRY I would like to refactor by introducing a method.
sb.Append("{name: 'Pull Ups', data: [");
foreach(var item in data)
{
sb.Append(prefix); prefix = ",";
sb.Append(item.PullUps);
}
sb.Append("]}");
sb.Append("{name: 'Push Ups', data: [");
prefix = string.Empty;
foreach (var item in data)
{
sb.Append(prefix); prefix = ",";
sb.Append(item.PushUps);
}
sb.Append("]}");
The method I need would be something like
void Data(ref StringBuilder sb, string title, IList<DataDto> data, ...)
And I would love my code to be something like:-
Data(ref sb, "Pull Ups", data, d=>d.PullUps);
Data(ref sb, "Push Ups", data, d=>d.PushUps);
Data(ref sb, "Squats", data, d=>d.Squats);
However I am struggling to find out how to do this. I know I need to use somthing similar along the lines of
private static void Data<T, TProp>(ref StringBuilder sb,
IList<T> data, Func<T, TProp> selector)
and inside (pusedocode)
foreach(var item in data) {
if (selector == ???)
sb.Append(??);
}
My DataDto is quite simply:-
public class DataDto
{
public virtual decimal PullUps { get; set; }
public virtual decimal PushUps { get; set; }
public virtual decimal Squats { get; set; }
...
}
I think, you want something like this:
You would call it like this: