Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Demonstrate the Example of LINQ Union() Method with StringComparer

  • Last Updated : 08 Dec, 2021

LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives a feature to .NET languages to create queries to retrieve data from the data source. Here in this article, we will demonstrate the example of the LINQ Union() method with the StringComparer.

1. Union() Method: This method is used to get the unique elements from the given lists. Or we can say that this method returns the union of two lists. The function takes two lists as input and then it will get the elements only once in repeating elements.

Syntax:

data1.Union(data2)

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

2. StringComparer: It is a class that is used to compare the strings that use some specific case or ordinal comparison rules. We can use this StringComparer in the Union() function to get the elements with string(case sensitive). It will compare the strings from the two lists and return the strings.

Syntax:

StringComparer.OrdinalIgnoreCase

If we are using union() function with StringComparer, then we have to first use Union() function then apply stringcomparer function with the given syntax.

Syntax:

data1.Union(data2, StringComparer.OrdinalIgnoreCase);

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

Example:

Input: { "Hello", "Geeks", "For", "Geeks" };
       { "Hello", "geeks" , "python" }
Output:
Hello 
Geeks 
For 
python 

Input: { "Hello", "Geeks" }
       { "Hello", "geeks" , "python" };
Output:
Hello 
Geeks 
python

Approach:

1. Create two lists of string types named data1 and data2.

2. Perform the Union Operation with StringComparer

data1.Union(data2, StringComparer.OrdinalIgnoreCase);

3. Display the results using foreach loop

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

Example:

C#




// C# program to illustrate how to use
// Union() Method with StringComparer in LINQ
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG{
 
static void Main(string[] args)
{
     
    // Create first list with 4 elements
    List<string> data1 = new List<string>(){
        "Hello", "Geeks", "For", "Geeks" };
         
    // Create first list with 3 elements
    List<string> data2 = new List<string>(){
        "Hello", "geeks", "python" };
 
    // Perform union operation
    var final = data1.Union(data2,
                            StringComparer.OrdinalIgnoreCase);
 
    // Display the result
    foreach(var j in final)
    {
        Console.WriteLine(j + " ");
    }
}
}

Output:

Hello 
Geeks 
For 
python 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!