List generic collection

G

Guest

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!!!
 
G

Guest

AVL said:
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);
}
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top