Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Demonstrate the Example of LINQ Intersect() Method with OrderBy() Method

  • Last Updated : 06 Dec, 2021

LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It provides the power to .NET languages to create queries to retrieve data from the data source. In this article we will demonstrate the example of the LINQ intersect() method with OrderBy() method.

1. intersect() Method: This is used to get the common elements from the two given lists. Or we can say that this method returns the intersection of two lists. It is available in both the Queryable and Enumerable classes.

Syntax:

data1.Intersect(data2)

Where data1 is the first list and data2 is the second list.

2. OrderBy() Method: The sole purpose of this method is to sort the given list of elements in ascending order. When you write the LINQ query using this method you need not write extra conditions to sort the array in ascending order.

Syntax:

data1.OrderBy(i => i)

Where i is the iterator. 

Now, we are combining the intersect() and OrderBy() method by first getting common elements using intersect() function, and then from the result we are getting the data in the ascending order with OrderBy() function and display the data using the iterator. So to do this we use the following query:

data1.Intersect(data2).OrderBy(i => i);

Where data1 is the first list and data2 is the second list

Example:

Input: { 10, 20, 30, 40, 50, 60, 70 }
       { 50, 60, 70, 80, 90, 100 }
Output:
50 
60 
70 

Input: { 10, 20, 30 }
       { 50, 60, 70 }
Output:
No Output

Approach:

1. Create and initialize two lists of integer type named as data1 and data2.

2. Now we use the below query to find the common elements from these lists and then sort them in ascending order.

final = data1.Intersect(data2).OrderBy(i => i);

3. Iterate the results using foreach loop.

foreach (var j in final)
{
    Console.WriteLine(j + " ");
}

Example:

C#




// C# program to illustrate how to use Intersect() method
// with OrderBy() method in LINQ
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG{
      
static void Main(string[] args)
{
      
    // Create first list
    List<int> data1 = new List<int>(){
        10, 20, 30, 40, 50, 60, 70 };
          
    // Create second list
    List<int> data2 = new List<int>() {
        50, 60, 70, 80, 90, 100 };
  
    // Finding the intersection of two lists and
    // then order them in ascending order.
    var final = data1.Intersect(data2).OrderBy(i => i);
  
    // Display the numbers
    Console.WriteLine("Final Result is: ");
    foreach(var j in final)
    {
        Console.WriteLine(j + " ");
    }
}
}


Output:

Final Result is: 
50 
60 
70 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!