您能否向我解释为什么执行以下代码后Selected
属性未更新为true
?为什么IEnumerable会丢失更新的数据?
使用的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
被调用时执行,从而创造新的项目,而不是返回包含我更新了项目的设定?