foreach loop question
Is there any other shorter/more efficient way to check and see if it is the last item in my Li开发者_如何学GostBox? 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 += ",";
}
}
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);
How about LINQ:
Label1.Text = string.Join(
",",
ListBox1.Items
.OfType<ListItem>()
.Where(item => item.Selected)
.Select(x => x.Value.ToString())
.ToArray()
);
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()
.
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
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();
精彩评论