Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - Excluding items from different list types

Tags:

vb.net

linq

Is there any way to select items in a list that aren't contained in another? For example:

list1 = From t In list1 Where Not list2.Contains(t.column1)

That gives me the error:

Value of type 'Integer' cannot be converted to '<anonymous type>'

which makes sense, since list2.Contains is expecting the same type as list2. However, the list types are different. I want only to select based on column comparisons.

like image 403
Daniel Avatar asked Dec 01 '22 07:12

Daniel


2 Answers

Well what does list2 actually contain? If you can express your query precisely, we can probably express it in LINQ. Without knowing what list1, list2 and column1 are it's hard to help.

What I would say is that List<T>.Contains is going to be O(n) for each item you check. If list2 is potentially non-small, you may well want to create a HashSet<T> - then each Contains call will be a lot faster.

But then again, when we know more about the situation we may well suggest a completely different solution. Please make the question as concrete as possible to get the best answer.

EDIT: If tvanfosson's solution works for you and if you're using LINQ to Objects, you've got a potential performance pit there. It would be better (IMO) to do the projection on list2 once and build a set:

Dim invalid = New HashSet(Of Integer)(list2.Select(Function(x) x.Id))
list1 = From t in list1 Where Not invalid.Contains(t.column1)
like image 197
Jon Skeet Avatar answered Dec 04 '22 23:12

Jon Skeet


Look at the .Except() extension method, combined with a projection:

list1 = list1.Except(list2.Select(Function(l) l.ID))
like image 43
Joel Coehoorn Avatar answered Dec 05 '22 01:12

Joel Coehoorn