C# 为什么IEnumerable会丢失更新的数据?

C# 为什么IEnumerable会丢失更新的数据?,c#,linq,C#,Linq,您能解释一下为什么在执行以下代码后,选定的属性没有更新为真 所使用的ListItem类型来自System.Web.UI.WebControls命名空间,是一个类(不是结构)。我相信FirstOrDefault函数返回一个实例引用,我可以在items可枚举项中更新和传递该引用 // produce list items out of the communities IEnumerable<ListItem> items = communities.Select(community =&

您能解释一下为什么在执行以下代码后,
选定的
属性没有更新为

所使用的
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!
//从社区中生成列表项
IEnumerable items=communities.Select(community=>newlistItem(community.Name,community.Id.ToString());
//如果需要,将右侧列表项标记为选中
如果(platform.CommunityId>0)
{
字符串strCommunityId=platform.CommunityId.ToString();
ListItem selectedItem=items.FirstOrDefault(item=>item.Value==strCommunityId);
如果(selectedItem!=null)selectedItem.Selected=true;
}
//现在项目不存储任何更新的项目!

这是因为每次调用
foreach
时都会执行枚举器,从而创建新项目,而不是返回包含我更新的项目的集合吗?

之所以会发生这种情况,是因为您使用
选择

IEnumerable<ListItem> items = communities
   .Select(community => new ListItem(community.Name, community.Id.ToString()));
IEnumerable items=社区
.Select(community=>newlistItem(community.Name,community.Id.ToString());

每次迭代项时都会创建新对象。

问题在于
IEnumerable
不可重复的。每次枚举时,您都在执行投影(
community=>newlistItem
),因此每次都是一个新的
ListItem
<代码>选择是一个非缓冲延迟投影

您只需添加一个
.ToList()
,就可以修复这里的所有问题,从而将数据强制添加到单个列表中

var items = communities.Select(
    community => new ListItem(community.Name, community.Id.ToString())
).ToList();
现在数据已经在列表中,您可以在列表上循环任意次数-它始终是相同的项目,更改将保留。

您的问题在于

IEnumerable<ListItem> items = communities
    .Select(community => new ListItem(community.Name, community.Id.ToString()));

您将观察到不同的结果。虽然它仍然是一个
IEnumerable
,但它将不再是一个懒散的评估对象,并且您在它中所做的更改将在同一
IEnumerable

的后续迭代中被观察到,我认为Marc Gravell的答案是正确的,但是您可以避免这种混淆,并在一行中完成它(可能导致另一种混乱)。;)

//从社区中生成列表项
IEnumerable items=社区。选择(社区=>
新列表项(community.Name、community.Id.ToString())
{ 
所选=社区.Id==平台.CommunityId
});
IEnumerable<ListItem> items = communities
    .Select(community => new ListItem(community.Name, community.Id.ToString()))
    .ToList();
// produce list items out of the communities
IEnumerable<ListItem> items = communities.Select(community => 
    new ListItem(community.Name, community.Id.ToString()) 
    { 
        Selected = community.Id == platform.CommunityId
    });