2013-04-10 109 views
0

有沒有辦法讓此代碼更有效?當索引不包含在另一個列表中時,從索引中刪除

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包含對象不是整數,因此所需要的對象的指數在list.Not知道如果includeRows.Remove()將使其減少或更高效,includeRows是隻是改成了HashSet。

for (int i = aList.Count - 1; i >= 0; i--) { 
        if (!includeRows.Contains(i + 1)) 
        { 
         aList.RemoveAt(i); 
         // includeRows.Remove(i + 1); 
        } 
} 
+0

讓你有索引的列表,你想從另一個列表中刪除未包含在索引中的項目? – Nahum 2013-04-10 05:18:31

+0

是----------- – tsukimi 2013-04-10 05:25:52

回答

3

大樓,我會做:

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

+0

+1是的,這樣會更高效,更具可讀性 – 2013-04-10 06:08:53

+0

這裏的哈希集獲得額外的性能。 – tsukimi 2013-04-10 06:12:20

3

下面是使用LINQ的Intersect方法的簡單方法:

aList = aList.Intersect(includeRows).ToList(); 

但有更好的表現,你可以在PSWG的答案使用RemoveAll代替

aList.RemoveAll(i => !includeRows.Exists(j => j == (i + 1)); 
+0

+1爲可讀解決方案 – basarat 2013-04-10 06:10:34

+0

謝謝你的好回答。相交是一個好主意,沒有想到這一點,但會堅持使用RemoveAll。 – tsukimi 2013-04-10 06:11:41

0
aList = aList.Intersect(includeRows).ToList<int>();