为什么IEnumerable丢失更新数据? [英] Why is IEnumerable losing updated data?
问题描述
您能否解释一下为什么执行以下代码后Selected
属性未更新为true
?
Could you explain to me why after executing the following code the Selected
property is not updated to true
?
所使用的ListItem
类型来自System.Web.UI.WebControls
命名空间,并且是一个类(不是结构.)我相信FirstOrDefault
函数返回对实例的引用,我可以对其进行更新并在items
中传递枚举.
The ListItem
type used comes from System.Web.UI.WebControls
namespace and is a class (not a struct.) I believed the FirstOrDefault
function returns a reference to an instance which I can update and pass around in the items
enumerable.
// 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
都会执行枚举器,从而创建新项目,而不是返回包含我更新的项目的集合吗?
Is that because the enumerator is executed each time a foreach
is called and thus creating new items instead of returning the set containing the item I updated?
推荐答案
问题是IEnumerable
是不可重复的.每次枚举(community => new ListItem
)都在执行投影(community => new ListItem
)-因此每次都是新的ListItem
. Select
是无缓冲的延迟投影.
The problem is that IEnumerable
is not repeatable. You are performing the projection (community => new ListItem
) every time it is enumerated - hence it is a new ListItem
each time. Select
is a non-buffered deferred projection.
您可以通过简单地添加.ToList()
来将此处的内容全部修复,以将数据强制放入单个列表中;
You can fix everything here with the simple addition of a .ToList()
to force the data into a single list;
var items = communities.Select(
community => new ListItem(community.Name, community.Id.ToString())
).ToList();
现在数据在列表中,您可以循环遍历列表多次-它始终是相同的项目,并且更改将被保留.
Now that the data is in the list, you can loop over the list any number of times - it'll always be the same items, and changes will be retained.
这篇关于为什么IEnumerable丢失更新数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!