[英]Whats wrong with my lambda expression
我想获取选中的值如1,3,4之类的checkedListbox字符串。 为此,我编写了一个lambda表达式:
private string GetCheckedIDs(CheckBoxList chkLst)
{
string chkedVal = string.Empty;
((List<string>)chkLst.Items.OfType<ListItem>().Where(s => s.Selected).Select(s => s.Value))
.ForEach(item => chkedVal = item + ",");
return chkedVal.Remove(chkedVal.LastIndexOf(","));
}
我得到的错误是:
Unable to cast object of type
'WhereSelectEnumerableIterator`2[System.Web.UI.WebControls.ListItem,System.String]' to type 'System.Collections.Generic.List`1[System.String]'.
lambda表达式没什么问题-问题是从IEnumerable<String>
到List<String>
您不能转换到列表,但这应该可以:
chkLst.Items.OfType<ListItem>()
.Where(s => s.Selected)
.Select(s => s.Value).ToList()
.ForEach(item => chkedVal = item + ",");
这是使用String.Join(String, IEnumerable<String>
)的更好的选择。 它仍然选择字符串,但避免字符串串联(和最后一个逗号!):
string chkedVal = String.Join(",", chkLst.Items.OfType<ListItem>()
.Where(s => s.Selected).Select(s => s.Value))
或者在.Net 3.5上,您没有那种方便的重载-您需要为String.Join(String, String[])
创建一个数组:
string chkedVal = String.Join(",", chkLst.Items.OfType<ListItem>()
.Where(s => s.Selected)
.Select(s => s.Value).ToArray())
该代码可能会编译,但是您会在运行时收到该错误。 这是因为Linq返回的IEnumerable<string>
实际上不是列表。 这是出于性能方面的考虑,否则Linq将不得不预先构建整个列表,而不是根据需要构建每个项目。
IEnumerable<T>
上有一个Linq方法,以强制Linq预先建立列表,尽管ToList
:
chkLst.Items
.OfType<ListItem>()
.Where(s => s.Selected)
.Select(s => s.Value)
.ToList()
.ForEach(item => chkedVal = item + ",");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.