LINQ Except Method

In LINQ, the Except method or operator is used to return only the elements from the first collection which are not present in the second collection.

 

Following is the pictorial representation of the LINQ Except method.

 

LINQ Except Method or Operator in C#, VB.NET with Example

 

As we discussed it return elements only from the first collection which do not exist in the second collection.

Syntax of LINQ Except Method

Following is the syntax of using LINQ Except method to get elements from the first list which do not exist in the second list.

 

C# Code

 

var result = arr1.Except(arr2);

VB.NET Code

 

Dim result = arr1.Except(arr2)

If you observe the above syntax we are comparing two lists “arr1”, “arr2” and getting elements using the Except method.

Example of LINQ Except Method

Following is the example of LINQ Except method to get elements from the first collection.

 

C# Code

 

using System;

using System.Linq;

using System.Collections.Generic;

 

namespace Linqtutorials

{

class Program

{

static void Main(string[] args)

{

string[] arr1 = { "Suresh", "Rohini", "Praveen", "Sateesh"};

string[] arr2 = { "Madhav", "Sushmitha", "Sateesh", "Praveen" };

var result = arr1.Except(arr2);

foreach (var item in result)

{

Console.WriteLine(item);

}

Console.ReadLine();

}

}

}

VB.NET Code

 

Module Module1

Sub Main()

Dim arr1 As String() = {"Suresh", "Rohini", "Praveen", "Sateesh"}

Dim arr2 As String() = {"Madhav", "Sushmitha", "Sateesh", "Praveen"}

Dim result = arr1.Except(arr2)

For Each item In result

Console.WriteLine(item)

Next

Console.ReadLine()

End Sub

End Module

If you observe above example, we applied Except method to “arr1” and “arr2” to get elements from first collection which are not exists in second collection.

Output of LINQ Except Method Example

Following is the result of the LINQ Except method example.

 

Suresh

Rohini

This is how we can use the LINQ Except method to get elements from the first collection which do not exist in the second collection.

Topics Covered