Reputation: 7764
I have two different types of Lists
class A
{
int number;
string name;
}
class B
{
int number;
}
List<A> a1;
List<B> b1;
And now both the lists were populated and now i want to remove items(number) in list a1 if that item(number) not exists in list b1.tried the below approach
a1.removeall(a=>b1.Exists(b1.number!=a1.number);
but the result is not as expected.Please help me...
Upvotes: 0
Views: 4234
Reputation: 160912
I think you want this:
a1.RemoveAll(a=> !b1.Any(b=> b.number == a.number));
Be aware though that this is O(n^2). A more performant approach would be using a HashSet<int>
(this might not matter for small lists but be aware of this for larger ones):
HashSet<int> bNums = new HashSet<int>(b1.Select(b => b.number));
a1.RemoveAll(a => !bNums.Contains(a.number));
Upvotes: 5