【发布时间】:2013-07-25 12:45:49
【问题描述】:
考虑下面的代码 sn-p
列出 orderList ; // 这个列表是预填充的
foreach (System.Web.UI.WebControls.ListItem item in OrdersChoiceList.Items) // OrdersChoiceList is of type System.Web.UI.WebControls.CheckBoxList
{
foreach (Order o in orderList)
{
if (item.id == o.id)
{
item.Selected = scopeComputer.SelectedBox;
break;
}
}
}
列表中有数千个项目,因此这些循环非常耗时。我们如何优化它?
此外,我们如何使用 LINQ 做同样的事情。我尝试使用连接操作,但无法根据“SelectedBox”设置“Selected”变量的值。现在我将 select 子句中的值硬编码为“true”,我们如何在 select 子句中传递和使用 SelectedBox 值
var v = (from c in ComputersChoiceList.Items.Cast<ListItem>()
join s in scopeComputers on c.Text equals s.CName
select c).Select(x=>x.Selected = true);
【问题讨论】:
-
我们可以在这里使用 LINQ 吗?
-
也许 if(OrdersChoiceList.Items.Select(i => i.id).Intersect( orderList.Select(i => i.id) ).Any()) ...
-
我感觉即使迭代“数千个项目”来更新它们的选定状态也不应该花很长时间。我感觉“耗时”方面是 GUI 层自行更新。编辑:哦,也许不是。没有在这里找到嵌套的 foreach 循环。绝对将您的
orderList更改为某种查找表,而不是为每个 ListItem 一次又一次地重新迭代它。 -
两个列表中是否有数千个项目?还是一个列表中有数千个,而另一个列表中则少得多?
-
两个列表都有大项目。
标签: c# asp.net performance linq