Home All Groups Group Topic Archive Search About

List generic collection

Author
16 Apr 2007 12:28 PM
AVL
hi,
i'm a new bie to .net 2.0..
ive used a list geeneric collection of strings in my code.

i would like to append all the strings to get a single value....
I've found the foreach() iteration method...for List collection..
any good sampels on how to use it and how is it beneficial than normal
iteration...
please help out!!!

Author
16 Apr 2007 4:19 PM
Göran Andersson
AVL wrote:
> hi,
> i'm a new bie to .net 2.0..
> ive used a list geeneric collection of strings in my code.
>
> i would like to append all the strings to get a single value....
> I've found the foreach() iteration method...for List collection..
> any good sampels on how to use it and how is it beneficial than normal
> iteration...
> please help out!!!

To append all strings in a list, use a StringBuilder:

StringBuilder builder = new StringBuilder();
foreach (string s in list) {
    builder.Append(s);
}
string result = builder.ToString();

Above you also see the use of the foreach loop. For comparison, here's
how it's done with a regular for loop:

StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.Count; i++) {
    builder.Append(list[i]);
}
string result = builder.ToString();

Which loop is better depends on what you want to do. One additional
advantage of the foreach loop is that it keeps track of the state of the
list you are iterating, so that if the list changes while you are
looping it, you get an exception.

--
Göran Andersson
_____
http://www.guffa.com

AddThis Social Bookmark Button