c# - foreach loop question -


is there other shorter/more efficient way check , see if last item in listbox? main goal here add selected items label, , add comma after every 1 last one. 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 second loop use:

label1.text = string.join("," , interestitems); 

p.s.

if you're using .net 3.5, need pass array of strings string.join(), :

label1.text = string.join("," , interestitems.toarray()); 

edit:

if want avoid looping do:

var selitems = listbox1.items.cast<listitem>()                        .where(item => item.selected)                        .select(item => item.tostring());  label1.text = string.join("," , selitems); 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -