atrljoe
atrljoe

Reputation: 8151

foreach loop question

Is there any other shorter/more efficient way to check and see if it is the last item in my ListBox? The main goal here is basically to add the selected items to a label, and add a comma after every one but the last one. Any suggestions?

        int sc = 0;
        List<string> interestitems = new List<string>();

        foreach (ListItem siitem in ListBox1.Items)
        {
            if (siitem.Selected == true)
            {
               interestitems.Add(siitem.Value.ToString());
            }
        }

        foreach (string inteitem in interestitems)
        {
            Label1.Text += inteitem;
            sc++;
            if (sc < interestitems.Count)
            {
                Label1.Text += ",";
            }
        }

Upvotes: 1

Views: 416

Answers (5)

digEmAll
digEmAll

Reputation: 57220

Instead of your second loop just use:

Label1.Text = string.Join("," , interestitems);

P.S.

if you're using .net 3.5, you need to pass an array of strings to string.Join(), then :

Label1.Text = string.Join("," , interestitems.ToArray());

EDIT:

If you want to completely avoid looping just do:

var selItems = ListBox1.Items.Cast<ListItem>()
                       .Where(item => item.Selected)
                       .Select(item => item.ToString());

Label1.Text = string.Join("," , selItems);

Upvotes: 11

JaredPar
JaredPar

Reputation: 755457

Why not just build up the string as you iterate during the first loop

var builder = new StringBuilder();
var first = true;
foreach (var item in ListBox1.Items) {
  if (item.Selected) {
    if (!first) {
      builder.Append(", ");
    }
    first = false;
    builder.Append(item.Value.ToString());
  }
}

Label1.Text = builder.ToString();

Upvotes: 0

Carlos Valenzuela
Carlos Valenzuela

Reputation: 834

I believe you can do this:

interestitems.IndexOf(inteitem);

Altought it worked me with other item types, may give you an idea. I haven't checked if it works with strings.

The you just have to eliminate the last one, with the index check if it's the last ones with interestitems.Count

Upvotes: 0

SLaks
SLaks

Reputation: 888177

You can replace all of your code with some LINQ:

Label1.Text = String.Join(", ",
              ListBox1.Items.Cast<ListItem>()
                            .Where(i => i.Selected)
                            .Select(i => i.Value.ToString())
              );

In .Net 3.5, you'll need to add .ToArray().

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

How about LINQ:

Label1.Text = string.Join(
    ",", 
    ListBox1.Items
            .OfType<ListItem>()
            .Where(item => item.Selected)
            .Select(x => x.Value.ToString())
            .ToArray()
);

Upvotes: 2

Related Questions