使用Lambda表达式遍历复选框列表 [英] Loop through Checkbox List using Lambda Expressions

查看:78
本文介绍了使用Lambda表达式遍历复选框列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复选框列表项列表.如何使用lambda表达式遍历这些表达式并将其文本属性读入字符串生成器对象?

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?

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

预先感谢

推荐答案

看这个人,这是获取列表项文本的最佳方法
look man this is the best way to get the text of the list items
List<ListItem> lst = new List<ListItem>();
foreach (ListItem item in CountryList.Items)
{
   lst.Add(item);
}

和lambda表达式用作:

and lambda exepression used as this:

ListItem itm = lst.First(p => p.Text == "blablabla");


您的意思是这样的吗?

You mean something like this?

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...


这有效!

This works!

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)));


这篇关于使用Lambda表达式遍历复选框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆