2012-03-19 44 views
0

我有兩個不同類型的列表刪除的項目,如果使用LINQ

class A 

{ 

int number; 

string name; 

} 

class B 

{ 

int number; 

} 

List<A> a1; 

List<B> b1; 

,現在被填充兩個列表,現在我想刪除列表A1項目(編號)在其他列表不存在如果該項目(編號)列表不存在b1.tried下面的方法

a1.removeall(a=>b1.Exists(b1.number!=a1.number); 

但結果並不如expected.Please幫我...

回答

2

我想你想要這樣的:

a1.RemoveAll(a=> !b1.Any(b=> b.number == a.number)); 

請注意,這是O(n^2)。一個更高性能的方法是使用HashSet<int>(這對小列表可能無關緊要,但對於較大列表可能並不重要):

HashSet<int> bNums = new HashSet<int>(b1.Select(b => b.number)); 
a1.RemoveAll(a => !bNums.Contains(a.number));