Click here to Skip to main content
15,891,633 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list of checkbox list items. How do I use lambda expressions to loop through these and get their text attributes read into a string builder object?
HTML
<asp:CheckBoxList ID="CountryList" runat="server" RepeatDirection="Vertical">
<asp:ListItem Text="Australia" Value="AU" />
<asp:ListItem Text="Belgium" Value="BG" />
<asp:ListItem Text="Canada" Value="CA" />
<asp:ListItem Text="France" Value="FR" />
</asp:CheckBoxList>
thanks in advance
Posted
Updated 23-Feb-12 20:47pm
v2
Comments
Nikhil_S 23-Feb-12 23:52pm    
please be specific with the Requirements and Explain why you are using Lambda Expressions ?
sunainanz 24-Feb-12 0:05am    
I just would like to find a new way to do this, instead of using the regular foreach loop. thanks.

This works!

XML
var p = (from item in CountryList.Items.Cast<ListItem>()
                     where item.Selected
                     select item).ToArray();

sb.AppendFormat("<strong>Countries selected:</strong> {0}<br />", String.Join(", ", p.ToStringArray(false)));
 
Share this answer
 
You mean something like this?

C#
StringBuilder sbWithOneItemTextPerLine = new StringBuilder();           
CheckBoxList.Items.ForEach(item => sbWithOneItemTextPerLine.AppendLine(item.Text);


Of course, only syntactic sugar - I wouldn't see fit to do it like this - you didn't explain you requirements...
 
Share this answer
 
Comments
sunainanz 26-Feb-12 19:33pm    
thanks, yes something like this. to add some elegance to code - that is all. This code however misses something. I cant find ForEach method or 'item' in C# version 4 that i am using. Does the code needs anything extra?
look man this is the best way to get the text of the list items
C#
List<ListItem> lst = new List<ListItem>();
foreach (ListItem item in CountryList.Items)
{
   lst.Add(item);
}
and lambda exepression used as this:
C#
ListItem itm = lst.First(p => p.Text == "blablabla");
 
Share this answer
 
v2
Comments
youssef_123 24-Feb-12 2:35am    
lambda exepression used as this:
ListItem itm = lst.First(p => p.Text == "blablabla");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900