How to use “not in” query with C# LINQ?

CsharpServer Side ProgrammingProgramming

Except operator are designed to allow you to query data which supports the IEnumerable<T< interface. Since all LINQ query expressions, and most LINQ queries, return IEnumerable<T<, these operators are designed to allow you to perform set operations on the results of a LINQ query.

The Except operator shows all the items in one list minus the items in a second list

Example 1

class Program{
   static void Main(string[] args){
      var listA = Enumerable.Range(1, 6);
      var listB = new List<int> { 3, 4 };
      var listC = listA.Except(listB);
      foreach (var item in listC){
         Console.WriteLine(item);
      }
      Console.ReadLine();
   }
}

Here in the above example we have 2 list and we are fetching only those result from the list A which are not present in listb

Output

1
2
5
6

Example 2

Using Sql like syntax

static void Main(string[] args){
   var listA = Enumerable.Range(1, 6);
   var listB = new List<int> { 3, 4 };
   var listC = from c in listA
   where !listB.Any(o => o == c)
   select c;
   foreach (var item in listC){
      Console.WriteLine(item);
   }
   Console.ReadLine();
}

Output

1
2
5
6
raja
Published on 05-Nov-2020 18:17:53
Advertisements