C# 代码优化以检查复选框列表中的某些项
考虑下面的代码片段 列出订单列表;//此列表是预先填充的C# 代码优化以检查复选框列表中的某些项,c#,asp.net,performance,linq,C#,Asp.net,Performance,Linq,考虑下面的代码片段 列出订单列表;//此列表是预先填充的 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
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);
var v=(来自ComputersChoiceList.Items.Cast()中的c)
在c上的scopeComputers中加入s。Text等于s.CName
选择c)。选择(x=>x.Selected=true);
我认为您需要消除嵌套迭代。正如您所说,两个列表都有一大组项。如果它们都有5000项,那么在最坏的情况下,您将看到25000000次迭代
对于每个列表项
,无需不断重复订单列表
。相反,创建一个ID查找,以便对每个ID进行快速O(1)查找。不确定点击范围计算机所涉及的工作。SelectedBox
,但这也可以在循环之外解决
bool selectedState = scopeComputer.SelectedBox;
HashSet<int> orderIDs = new HashSet<int>(orders.Select(o => o.id));
foreach (System.Web.UI.WebControls.ListItem item in OrdersChoiceList.Items)
{
if (orderIDs.Contains(item.id))
item.Selected = selectedState;
}
同样,不确定您的确切类型/用法。您也可以用一个LINQ查询来简化这一点,但我认为(从性能上讲)您不会看到太多的改进。我还假设每个
ListItem.Text
条目都有一个匹配的ScopeComputer
,否则在访问scopeComputersSelectedState[item.Text]
时会出现异常。如果没有,那么将其更改为执行TryGetValue
查找应该是一个简单的练习。我们可以在这里使用LINQ吗?可能是(OrdersChoiceList.Items.Select(i=>i.id).Intersect(orderslist.Select(i=>i.id)).Any()…我觉得迭代“数千项”也不需要太长时间以更新其选定状态。我觉得“耗时”的方面是GUI层本身的更新。编辑:哦,也许不是。这里没有发现嵌套的foreach循环。一定要将您的orderList
更改为某种类型的查找表,而不是对每个列表项一次又一次地重复它。这两个列表中是否都有数千项?或者一个列表中有数千个项目,而另一个列表中的项目则少得多?这两个列表都有大型项目。
HashSet<int> orderIDs = new HashSet<int>(orders.Select(o => o.id));
Dictionary<string, bool> scopeComputersSelectedState =
scopeComputers.ToDictionary(s => s.CName, s => s.Selected);
foreach (System.Web.UI.WebControls.ListItem item in OrdersChoiceList.Items)
{
if (orderIDs.Contains(item.id))
item.Selected = scopeComputersSelectedState[item.Text];
}