NOT IN for LINQ?

Is there a way to filter employees by group: for example:

List<String> notInGroups = GetNotInGroups(); var list = from p in employees where p.Group.Name notin(notInGroups) select p; 

Is there a way to do something like this?

thanks

+4
source share
6 answers

You can do! Contains, for example:

 var list = from p in employees where !notInGroups.Contains(p.Group.Name) select p; 
+7
source

Failed to check, but would there be something like this work?

 var notInGroups = GetNotInGroups(); var list = from p in employees where notInGroups.Contains(p.Group.Name) == false select p; 
+2
source

Try where !notInGroups.Contains(p.Group.Name); as your suggestion is WHERE .

+1
source

Try the following:

 var result = list1.Except(list2); 
+1
source

You can do something like this.

 List<String> notInGroups = GetNotInGroups(); var list = from p in employees where !(notInGroups.Contains(p.Group.Name)) select p; 
+1
source

List not particularly suitable for searching the collection to see if it contains a specific element, what exactly do you want to do. Although writing code is quite simple (there are already many answers showing how), you will greatly benefit from using a more appropriate data structure that can be more efficiently searched for, for example, HashSet :

 var notInGroups = new HashSet<string>(GetNotInGroups()); var list = from p in employees where !notInGroups.Contains(p.Group.Name) select p; 
+1
source

All Articles