2011-11-03 62 views
2

任何人都可以幫助我將這段代碼改回一個簡單的for循環嗎?逆向工程聚合爲一個簡單的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>")); 

代碼遍歷數組「元素」的元素並創建一個選項列表。我想做一些不同的處理,但我不知道如何對此進行反向工程。任何建議將非常受歡迎。

+1

你的意思是,重寫,而不是反向工程。此外,[XY問題]的經典案例(http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem);你爲什麼不告訴我們你需要做什麼不同的處理? – sehe

+1

「價值」屬性的值可能會錯過開盤報價 – sehe

回答

2

集合只是遍歷列表中的項目,並將委託的結果傳遞給下一個委託調用。

第一個參數指定開始的初始值。

foreach (string description in sT.Description) 
{ 
    text += "<option value=" + string.Format("{0:00}", j) + "'>" + j++ + ". " + description+ "</option>"; 
} 
0

貌似這個

foreach (string s in sT.Description) 
      text = text + ("<option value=" + string.Format("{0:00}", j) + "'>" + j++ + ". " + s + "</option>"); 
1
foreach(var description in sT.Description) 
{ 
    text += String.Format("<option value={0:00}'>{1}.{2}</option>", 
          j, 
          j++, 
          description) 
} 
-2

您可以使用此

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

,但它與問題沒有關係。這看起來像一個非常糟糕的重複'string.Join'給我。另外,你是否在現實生活中像這樣縮進你的代碼? – sehe

+1

但是,以後請勿將代碼示例留在未格式化的混亂中,這不是由我來決定答案的技術準確性或正確性。下次它將被刪除,或者您可能因爲低質量貢獻而被暫停。你可以在這裏找到更多關於如何使用markdown編輯器的信息:http://stackoverflow.com/editing-help – Kev

0

我可以建議

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