[英]Whats wrong with my lambda expression
I want to get string of checkedListbox selected values like 1,3,4. 我想获取选中的值如1,3,4之类的checkedListbox字符串。 To achieve this i have written a lambda expression: 为此,我编写了一个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(","));
}
The error I am getting is: 我得到的错误是:
Unable to cast object of type
'WhereSelectEnumerableIterator`2[System.Web.UI.WebControls.ListItem,System.String]' to type 'System.Collections.Generic.List`1[System.String]'.
Nothing is wrong with your lambda expression - the problem is the casting from IEnumerable<String>
to List<String>
You can't cast to a list, but this should work: lambda表达式没什么问题-问题是从IEnumerable<String>
到List<String>
您不能转换到列表,但这应该可以:
chkLst.Items.OfType<ListItem>()
.Where(s => s.Selected)
.Select(s => s.Value).ToList()
.ForEach(item => chkedVal = item + ",");
Here is a better option, using String.Join(String, IEnumerable<String>
) . 这是使用String.Join(String, IEnumerable<String>
)的更好的选择。 It still selects the strings, but avoids string concatenation (and the last comma!): 它仍然选择字符串,但避免字符串串联(和最后一个逗号!):
string chkedVal = String.Join(",", chkLst.Items.OfType<ListItem>()
.Where(s => s.Selected).Select(s => s.Value))
Or on .Net 3.5 you don't have that handy overload - you need to create an array for String.Join(String, String[])
: 或者在.Net 3.5上,您没有那种方便的重载-您需要为String.Join(String, String[])
创建一个数组:
string chkedVal = String.Join(",", chkLst.Items.OfType<ListItem>()
.Where(s => s.Selected)
.Select(s => s.Value).ToArray())
The code may compile, but you'll get that error at run time. 该代码可能会编译,但是您会在运行时收到该错误。 This is because the IEnumerable<string>
returned by Linq isn't actually a list. 这是因为Linq返回的IEnumerable<string>
实际上不是列表。 This is for performance reasons, otherwise Linq would have to build the whole list up front, instead of building each item as it is needed. 这是出于性能方面的考虑,否则Linq将不得不预先构建整个列表,而不是根据需要构建每个项目。
There is a Linq method on IEnumerable<T>
to force Linq to build the list up front, though - ToList
: 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.