I have the following code that is used to create data for a jquery graph. However, it is quite repetitive and in order to preserve DRY, I would like to reorganize 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("]}");
I need a method similar to
void Data(ref StringBuilder sb, string title, IList<DataDto> data, ...)
And I would like 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 figure out how to do this. I know that I need to use something similar line by line
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 pretty simple: -
public class DataDto
{
public virtual decimal PullUps { get; set; }
public virtual decimal PushUps { get; set; }
public virtual decimal Squats { get; set; }
...
}