Using a lambda inside a method and match against a List
I have the following code that is used for producing data for a jquery graph. However it is quite repetitive and in order to k开发者_如何学编程eep 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:
void YourMethod<TItem, TProp>(StringBuilder sb, string name, IList<TItem> data,
Func<TItem, TProp> selector)
{
var prefix = "";
sb.Append("{name: '"+name+"', data: [");
foreach(var item in data)
{
sb.Append(prefix);
prefix = ",";
sb.Append(selector(item).ToString());
}
sb.Append("]}");
}
You would call it like this:
YourMethod(sb, "Pull Ups", data, d=>d.PullUps);
YourMethod(sb, "Push Ups", data, d=>d.PushUps);
YourMethod(sb, "Squats", data, d=>d.Squats);
What about just simplifying the code you have?
sb.Append("{name: 'Pull Ups', data: [");
sb.Append(String.Join(",", myExercises.Select(e=>e.PullUps));}
sb.Append("]}");
sb.Append("{name: 'Push Ups', data: [");
sb.Append(String.Join(",", myExercises.Select(e=>e.PushUps));}
sb.Append("]}");
Also, can you have fractional pull ups, push ups or squats? Is a decimal a bit overkill?
精彩评论