简体   繁体   中英

Remove item from IQueryable from List

I have 2 tables in my database Products and PremiumProducts for an ASP Net application.

I retrieve products with a simple query

IQueryable<Product> query = from p in myDataContext.Products select p;

I have a List of PremiumProducts (which contains the ID of a Product ). I am attempting to remove the IDs in the PremiumProducts list from the query above but not sure if there is a simple way or if i need to convert all the PremiumProducts to a Product first? I attempted this

List<PremiumProducts> premiumProducts;

query = from p in query where (premiumProducts.Contains(p.ID)) select p;

but of course this brings back all sorts of casting errors.

Is there a simple way to remove the PremiumProducts from the query above or do i need to convert the PremiumProducts to a Product , store the ID and then attempt to remove the query with these IDs?

Rather than:

query = from p in query where (premiumProducts.Contains(p.ID)) select p;

I would suggest:

query = from p in query where (!premiumProducts.Select(z => z.ID).Contains(p.ID)) select p;

The key differences:

  1. Using ! (since you want to exclude those that are in premiumProducts ).
  2. Using premiumProducts.Select(z => z.ID) to ensure that the contains is against the ID not the object (just avoiding your casting issues).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM