LINQ Except Method

  Total Views : 192
  Comments : 0
 
  Keywords : Linq except set operator in c# / vb.net with example, How to use linq except operator to get elements first collection in c# / vb.net with example, Linq enumerable.except method with example

Here we will learn LINQ Set method or operator in c#, vb.net with example and how to use LINQ Set method / operator to get elements from first collection which are not exists in second collection in c#, vb.net with example.

LINQ Except Method

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

 

Following is the pictorial representation of LINQ Except method.

 

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

 

As we discussed it return elements only from first collection which are not exists in second collection.

Syntax of LINQ Except Method

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

 

C# Code

 

var result = arr1.Except(arr2);

VB.NET Code

 

Dim result = arr1.Except(arr2)

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

Example of LINQ Except Method

Following is the example of LINQ Except method to get elements from 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 LINQ Except method example.

 

Suresh

Rohini

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

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User