你能解释一下为什么在执行下面的代码后Selected属性没有更新到true?
使用的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!
Run Code Online (Sandbox Code Playgroud)
这是因为每次foreach调用a时都会执行枚举器,从而创建新项而不是返回包含我更新的项的集合?
Mar*_*ell 17
问题是,IEnumerable是不可重复的.您每次枚举时都在执行投影(community => new ListItem)- 因此每次都是新的.是一个非缓冲的延迟投影.ListItemSelect
您可以通过简单添加a .ToList()来修复所有内容,以将数据强制转换为单个列表;
var items = communities.Select(
community => new ListItem(community.Name, community.Id.ToString())
).ToList();
Run Code Online (Sandbox Code Playgroud)
既然数据在列表中,您可以循环遍历列表 - 它始终是相同的项目,并且将保留更改.
发生这种情况是因为您使用了Select:
IEnumerable<ListItem> items = communities
.Select(community => new ListItem(community.Name, community.Id.ToString()));
Run Code Online (Sandbox Code Playgroud)
每次您遍历项目时都会创建新对象。
你的问题是
IEnumerable<ListItem> items = communities
.Select(community => new ListItem(community.Name, community.Id.ToString()));
Run Code Online (Sandbox Code Playgroud)
创建一个惰性计算的IEnumerable -即,每次枚举时,communities都会重新枚举原始序列,并Select对该序列中的每个项目重新执行投影。
如果.ToList()在末尾粘贴a ,请将行更改为:
IEnumerable<ListItem> items = communities
.Select(community => new ListItem(community.Name, community.Id.ToString()))
.ToList();
Run Code Online (Sandbox Code Playgroud)
您会看到不同的结果。虽然它仍然是an IEnumerable,但它不再是惰性评估的,并且您在其中所做的更改将在以后的相同迭代中可见IEnumerable。