How to make a NOT IN in LINQ?

8

I wanted to know how to do NOT IN in the next query

 select * from WFRules 
          where (Class = 'DoDesign' or ParentId = 0) 
            and ParentType not in (5,8,9,10,11) 
            and Type not in (5,8,9,11,15,33,34,35,37,38,39,40,41)

So far I have this:

   var rulcon = (from w in db.WFRules 
                 where w.Class == "DoDesign" || w.ParentId == 0
                 select w).ToList();     

Try to test with the contains but it does not work

This is the table:

    
asked by Andromeda 20.01.2016 в 20:53
source

3 answers

6

You must have a list with the values to ignore var types= {1, 2, 3};

The query would be as follows:

var rulcon = (from w in db.WFRules where w.Class == "DoDesign" ||
              w.ParentId == 0 &&  types.Contains(w.Type) select w).ToList();

This way you are doing an IN, if you want to make a Not IN you must use the character ! to deny the condition types.Contains(w.Type)

    
answered by 20.01.2016 / 21:06
source
4

This is one way:

var tipos = new Int32[] { 5, 8, 9, 11, 15, 33, 34, 35, 37, 38, 39, 40, 41 };
var parentTipos = new Int32[] { 5, 8, 9, 10, 11 };

var rulcon = (from w in db.WFRules 
              where 
                (w.Class == "DoDesign" || w.ParentId == 0) &&
                !parentTipos.Contains(w.ParentType) &&
                !tipos.Contains(w.Type)
              select w).ToList();     
    
answered by 20.01.2016 в 21:14
0

This is a more elegant form and the one recommended even for the database engine when you query a BD.

var tipos = new Int32[] { 5, 8, 9, 11, 15, 33, 34, 35, 37, 38, 39, 40, 41 };

var parentTipos = new Int32[] { 5, 8, 9, 10, 11 };

var res = tipos.Where(w => !parentTipos.Any(x => w == x)).ToList();
    
answered by 18.05.2018 в 00:37