簡體   English   中英

將聚合反向工程為簡單的for循環

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM