Implement “not in” (aka “not exists”) logic in LINQ

前端 未结 1 403
醉酒成梦
醉酒成梦 2021-01-28 12:38

Setup

  1. I have two List\'s.
  2. The data is un-normalized and from different sources which explains the convolution in the desired logic
1条回答
  •  醉话见心
    2021-01-28 13:18

    SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)

    Note: IN and NOT IN use the same function in the LINQ query, but it just use a ! (not) symbol for it. Here is the graphical representation:

    enter image description here

    You use, where .Contains( )

    var myProducts = from p in db.Products
                     where productList.Contains(p.ProductID)
                     select p;
    

    Or you can have a list predefined as such:

    var ids = {1, 2, 3};
    
    var query = from item in context.items
                where ids.Contains( item.id )
                select item;
    

    For the 'NOT' case, just add the '!' operator before the 'Contains' statement.

    0 讨论(0)
提交回复
热议问题