你能向我解释一下为什么执行以下代码后Selected
属性未更新为true
?
The ListItem
使用的类型来自System.Web.UI.WebControls
命名空间并且是一个类(不是结构)。我相信FirstOrDefault
函数返回对实例的引用,我可以更新该实例并在items
可数。
// produce list items out of the communities
IEnumerable<ListItem> items = communities.Select(community => new ListItem(community.Name, community.Id.ToString()));
// mark the right list item as selected, if needed
if (platform.CommunityId > 0)
{
string strCommunityId = platform.CommunityId.ToString();
ListItem selectedItem = items.FirstOrDefault(item => item.Value == strCommunityId);
if (selectedItem != null) selectedItem.Selected = true;
}
// now items do not store any updated item!
这是因为每次执行枚举器foreach
被调用并因此创建新项目而不是返回包含我更新的项目的集合?
问题是IEnumerable
is 不可重复。您正在执行投影(community => new ListItem
) 每次被枚举时- 因此这是一个新的ListItem
每一次。Select
是非缓冲的延迟投影。
您可以通过简单添加一个来修复这里的所有内容.ToList()
将数据强制放入单个列表中;
var items = communities.Select(
community => new ListItem(community.Name, community.Id.ToString())
).ToList();
现在数据已在列表中,您可以循环list任意多次 - 它将始终是相同的项目,并且更改将被保留。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)