ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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

Here, we are going to learn about the Except method in Linq and its C# implementation.
Submitted by Nidhi, on August 27, 2020

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.

Program:

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.