C# - Example of Except Method in LINQ

Learn about the Except method in Linq and its C# implementation. By Nidhi Last updated : April 01, 2023

Here we will create two lists list1 and list2 and then find the elements that are not present in list2 but present in list1 using Except() Method in Linq query.

C# program to demonstrate the example of Except method in LINQ

The source code to find the sum of array elements using the predefine method is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the 
//Except() method in Linq.

using System;
using System.Linq;
using System.Collections.Generic;

class Program {
  static void Main(string[] args) {
    List < int > list1 = new List < int > ();
    List < int > list2 = new List < int > ();

    list1.Add(1);
    list1.Add(2);
    list1.Add(3);
    list1.Add(4);
    list1.Add(5);
    list1.Add(6);

    list2.Add(1);
    list2.Add(3);
    list2.Add(5);
    list2.Add(6);
    list2.Add(7);
    list2.Add(8);

    var query = (from num in list1 select num)
      .Except(list2).ToList();

    foreach(var val in query) {
      Console.WriteLine(val);
    }
  }
}

Output

2
4
Press any key to continue . . .

Explanation

In the above program, we created two lists list1 and list2 using generic List collection. Then add the elements in lists using the Add() method.

var query = (from num in list1
        select num)
        .Except(list2).ToList();

Using the above code, we find those elements that are present in list1 but not present in list2 using the Linq query.

foreach (var val in query)
{
    Console.WriteLine(val);
}

Using the above code, we printed the query result on the console screen.

C# LINQ Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.