简体   繁体   中英

Reverse engineering an aggregate into a simple for loop

Can anyone help me change this code back to a simple for loop?

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

The code goes through the elements of an array "Description" and creates a list of options. I would like to do some different processing but I am not sure how to reverse engineer this. Any suggestions would be very welcome.

Aggregate simply loops through the items of the list and passes the result of the delegate to the next call to the delegate.

The first parameter specifies the initial value to start with.

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

Looks like this

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

Might I suggest

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

Or, rather:

text += sT.Description.Aggregate(new StringBuilder(), 
        (a,s) => a.AppendFormat("<option value='{0:00}'>{1}. {2}</option>", j, j++, s)
    ).ToString();

I think it is clearer, and certainly more efficient. However, if you insist on having a loop for this, you can use:

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

You can use this

.Aggregate(new StringBuilder(),
            (a, b) => a.Append(", " + b.ToString()),
            (a) => a.Remove(0, 2).ToString()); 

Or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM