Thursday, January 7, 2010

List and ForEach

Let's say you have a List of strings in C# and you add each element of the List to a StringBuilder.

StringBuilder sb = new StringBuilder();
List  <string> list = new List <string>();
list.add("one");
list.add("two");
list.add("three");

You could do the following loop:

foreach(var item in list){
  sb.Append(item); 
}
An alternative method to achieve the same functionality would go like this:
list.ForEach(item =>sb.Append(item));

With this method you save 2 lines of code and improve readability.

No comments:

Post a Comment