Set Operators in LINQ

Set operators in LINQ are used to perform set function on sequences. There are four types of set operators in C#.

  • Concat
  • Union
  • Intersect
  • Except

Concat and Union

The Concat operator in LINQ is used to concatenate two sequences. On the other hand, the Union operator also concatenates the sequences but it removes duplicates from the two sequences. Have a look at the following example to see how Concat and Union work.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main()   {
            string[] sequence1 = { "Joseph", "Juana", "Sara", "Mike", "Angel", "Victoria" };
            string[] sequence2 = { "Joseph", "Merry", "Sara", "Halen", "Angel", "Elizabeth" };

            // Concatenating sequence1 and sequence2
            IEnumerable<string> output = sequence1.Concat(sequence2);

            // All the items from sequence1 and sequence2 will be displayed
            foreach (string s in output) Console.WriteLine(s);

            Console.WriteLine("=====================");
            // Taking union of sequence1 and sequence2
            output = sequence1.Union(sequence2);

            // All items from sequence1 and sequence2 will be displayed
            //Except duplicates
            foreach (string s in output)   Console.WriteLine(s);
            Console.ReadKey();
        }
    }
}

Download the code

Intersect and Except

The Intersect operator returns those items which are common in both the sequences. The Except operator returns all the items from the first sequence except those which also exit in the second sequence. Have a look at the example of Concat and Except operators.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            string[] sequence1 = { "Joseph", "Juana", "Sara", "Mike", "Angel", "Victoria" };
            string[] sequence2 = { "Joseph", "Merry", "Sara", "Halen", "Angel", "Elizabeth" };

            // Taking intersect of sequence1 and sequence
            IEnumerable<string> output = sequence1.Intersect(sequence2);

            // All the items common from sequence1 and sequence2 will be displayed
            foreach (string s in output)  Console.WriteLine(s);

            Console.WriteLine("=====================");
            // Taking Except of sequence1 and sequence2
            output = sequence1.Except(sequence2);

            // All items from sequence1 which are not in sequence2 will be displayed
            foreach (string s in output) Console.WriteLine(s);
            Console.ReadKey();
        }
    }
}

Download the code

<<< Element Operators in LINQ
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .