[英]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.