Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you do a "not in" query with LINQ?

Tags:

c#

linq

I have two collections which have property Email in both collections. I need to get a list of the items in the first list where Email does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?

So far I have a join, like...

var matches = from item1 in list1 join item2 in list2 on item1.Email equals item2.Email select new { Email = list1.Email }; 

But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.

like image 363
Brennan Avatar asked Oct 08 '08 17:10

Brennan


People also ask

What is LINQ used for in NoSQL?

LINQ can be used for querying several popular NoSQL databases (at least those with . NET clients). For example: Using LINQ to Query RavenDB.

How do I Select a query in LINQ?

Select query in LINQ Select method is used to select one or more items from collection or list object, here we see some example of linq select statement. variableName. Select(s => s.Name); There are various ways we can select some records or single record from a collection object.

Can we use like in LINQ query C#?

In LINQ to SQL, we don't have a LIKE operator, but by using contains(), startswith(), and endswith() methods, we can implement LIKE operator functionality in LINQ to SQL. The following table shows more details regarding operators we used to achieve LINQ to SQL Like operators.


2 Answers

You want the Except operator.

var answer = list1.Except(list2); 

Better explanation here: https://docs.microsoft.com/archive/blogs/charlie/linq-farm-more-on-set-operators

NOTE: This technique works best for primitive types only, since you have to implement an IEqualityComparer to use the Except method with complex types.

like image 105
Echostorm Avatar answered Oct 17 '22 10:10

Echostorm


I don't know if this will help you but..

NorthwindDataContext dc = new NorthwindDataContext();     dc.Log = Console.Out;  var query =         from c in dc.Customers         where !(from o in dc.Orders                 select o.CustomerID)                .Contains(c.CustomerID)         select c;  foreach (var c in query) Console.WriteLine( c ); 

from The NOT IN clause in LINQ to SQL by Marco Russo

like image 24
Robert Rouse Avatar answered Oct 17 '22 11:10

Robert Rouse