13

I have a list of Products like this

var r = db.Products.Where(x => x.Sites
                                .Where(z => z.Key == associatedProducts.Key)
                                .Any()
                  ).ToList()

There is an entity called Products, I want to get all elements from products except those exist in associatedProducts.Products

How can i do that ?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Mohamed Naguib
  • 1,720
  • 6
  • 23
  • 32

3 Answers3

23

The following query works if associatedProducts list is fetched using EF in a previos query.

var temp = db.Products.ToList().Except(associatedProducts).ToList();

otherwise, if associatedProducts is a list which has not been fetched using EF (assuming Key is an integer);

List<int> tempIdList = associatedProducts.Select(q => q.Key ).ToList();
var temp = db.Products.Where(q => !tempIdList.Contains(q.Key));
daryal
  • 14,643
  • 4
  • 38
  • 54
0
            var query = from p in db.Products
                        where !(from a in associatedProducts.Products
                                select a.Products)
                                .Contains(p.Key)
                        select p;

I didn't test the query, but it should look like this.

You should have a look at how you can use "not in" in linq:
How would you do a "not in" query with LINQ?

Community
  • 1
  • 1
Petrutiu Mihai
  • 565
  • 4
  • 14
-4

You can load the list of products that you want to exclude, and then .Exclude() it from the list of all products.

dutzu
  • 3,883
  • 13
  • 19