将聚合反向工程为简单的for循环

本文关键字:简单 for 循环 | 更新日期: 2023-09-27 18:13:06

谁能帮我把这段代码改回一个简单的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>"));

代码遍历数组"Description"中的元素,并创建一个选项列表。我想做一些不同的处理,但我不确定如何逆向工程。欢迎提出任何建议。

将聚合反向工程为简单的for循环

Aggregate只是循环遍历列表中的项,并将委托的结果传递给下一次对委托的调用。

第一个参数指定起始值

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();  
}