在方法内使用 lambda 并与列表匹配
我有以下代码用于生成 jquery 图表的数据。然而它是相当重复的,为了保持 DRY 我想通过引入一种方法来重构。
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("]}");
我需要的方法类似于
void Data(ref StringBuilder sb, string title, IList<DataDto> data, ...)
我希望我的代码类似于:-
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);
但是我正在努力找出如何做到这一点。我知道我需要使用类似的东西
private static void Data<T, TProp>(ref StringBuilder sb,
IList<T> data, Func<T, TProp> selector)
(pusedocode),
foreach(var item in data) {
if (selector == ???)
sb.Append(??);
}
我的 DataDto 非常简单:-
public class DataDto
{
public virtual decimal PullUps { get; set; }
public virtual decimal PushUps { get; set; }
public virtual decimal Squats { get; set; }
...
}
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; }
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想,你想要这样的东西:
你会这样称呼它:
I think, you want something like this:
You would call it like this:
简化现有的代码怎么样?
另外,你可以做分段引体向上、俯卧撑或深蹲吗?小数是不是有点过分了?
What about just simplifying the code you have?
Also, can you have fractional pull ups, push ups or squats? Is a decimal a bit overkill?