Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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; }
 ...
}
like image 845
Rippo Avatar asked Jul 18 '26 03:07

Rippo


2 Answers

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);
like image 142
Daniel Hilgarth Avatar answered Jul 19 '26 17:07

Daniel Hilgarth


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?

like image 30
Lazarus Avatar answered Jul 19 '26 15:07

Lazarus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!