[英]Reverse engineering an aggregate into a simple for loop
谁能帮助我将此代码改回简单的for循环?
public class sT
{
public string[] Description { get; set; }
}
text = sT.Description.Aggregate(text, (current, description) =>
current + ("<option value=" + string.Format("{0:00}", j) + "'>" + j++ + ". " + description+ "</option>"));
该代码遍历数组“描述”的元素,并创建选项列表。 我想做一些不同的处理,但是我不确定如何对它进行反向工程。 任何建议将非常欢迎。
聚合简单地循环遍历列表的各项,并将委托的结果传递给委托的下一个调用。
第一个参数指定开始的初始值。
foreach ( string description in sT.Description )
{
text += "<option value=" + string.Format("{0:00}", j) + "'>" + j++ + ". " + description+ "</option>";
}
foreach(var description in sT.Description)
{
text += String.Format("<option value={0:00}'>{1}.{2}</option>",
j,
j++,
description)
}
看起来像这样
foreach (string s in sT.Description)
text = text + ("<option value=" + string.Format("{0:00}", j) + "'>" + j++ + ". " + s + "</option>");
我可能会建议
foreach (string s in sT.Description)
text += string.Format("<option value='{0:00}'>{1}. {2}</option>", j, j++, s);
更确切地说:
text += sT.Description.Aggregate(new StringBuilder(),
(a,s) => a.AppendFormat("<option value='{0:00}'>{1}. {2}</option>", j, j++, s)
).ToString();
我认为这更清晰,当然也更有效率。 但是,如果您坚持为此循环,则可以使用:
var sb = new StringBuilder();
foreach (string s in sT.Description)
sb.AppendFormat("<option value='{0:00}'>{1}. {2}</option>", j, j++, s);
text += sb.ToString();
你可以用这个
.Aggregate(new StringBuilder(),
(a, b) => a.Append(", " + b.ToString()),
(a) => a.Remove(0, 2).ToString());
要么
public static String Aggregate(this IEnumerable<String> source, Func<String, String, String> fn)
{
StringBuilder sb = new StringBuilder();
foreach (String s in source)
{
if (sb.Length > 0)
sb.Append(", ");
sb.Append(s);
}
return sb.ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.