有没有办法让这段代码更有效率?
if (includeRows != null && includeRows.Count > 0)
{
for (int i = aList.Count - 1; i >= 0; i--)
{
if (!includeRows.Exists(j => j == (i + 1)))
{
aList.RemoveAt(i);
includeRows.Remove(i + 1);
}
}
}
这就是我所做的,aList包含的对象不是整数,所以需要列表中对象的索引。不确定includeRows.Remove()是否会使它更低或更高效,includeRows只是改为a HashSet的。
for (int i = aList.Count - 1; i >= 0; i--) {
if (!includeRows.Contains(i + 1) )
{
aList.RemoveAt(i);
// includeRows.Remove(i + 1);
}
}
答案 0 :(得分:3)
使用Linq的Intersect
方法,这是一个简单的方法:
aList = aList.Intersect(includeRows).ToList();
但为了获得更好的效果,您可以使用RemoveAll
代替
aList.RemoveAll(i => !includeRows.Exists(j => j == (i + 1));
答案 1 :(得分:3)
在p.s.w.g的答案基础上,我会这样做:
HashSet<int> includeRowsFaster = new HashSet<int>(includeRows);
aList.RemoveAll(i => !includeRowsFaster.Contains(i + 1));
获得最高效的性能和可读性。在includeRows中查找元素是O(n)复杂度操作。您可以使用散列集而不是向量(数组或列表)实现将其显着减少到O(log(n))。
有关Hashset与列表性能的讨论,请参阅此内容:https://stackoverflow.com/a/10762995/390330
答案 2 :(得分:0)
aList = aList.Intersect(includeRows).ToList<int>();