Part - 15 LINQ Concat Method
Part - 15 LINQ Concat Method
The LINQ Concat Method in C# is used to concatenate two sequences into one sequence. The point
that you need to remember is it is used to concatenate two same types of sequences or collections
and return a new sequence or collection without removing the duplicate elements. There is only one
version available for this method whose signature is given below.
//Method Syntax
var MS = sequence1.Concat(sequence2);
//Query Syntax
var QS = (from num in sequence1
select num)
.Concat(sequence2).ToList();
Console.ReadLine();
}
}
}
Output: 1 2 3 4 2 4 6 8
If you notice in the above output then you will see that the duplicate elements i.e. 2 and 4 are not
removed. The Concat Method will throw an exception if any of the sequences is null. In the below
example, the second sequence is null and while performing the concatenate operation using the LINQ
Concat Operator it will throw an exception.
using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
List<int> sequence1 = new List<int> { 1, 2, 3, 4 };
List<int> sequence2 = null;
Console.ReadLine();
}
}
}
Now run the application and you will get the following exception.
//Method Syntax
var MS = StudentCollection1.Concat(StudentCollection2).ToList();
//Query Syntax
var QS = (from std in StudentCollection1
select std).Concat(StudentCollection2).ToList();
Console.ReadKey();
}
}
}
Now, run the application and you will get the following output which shows the duplicate elements as
well.
Now let us concatenate the above two sequences using the Union operator and observe what
happened.
What is the Difference Between LINQ Concat and Union Method in C#?
The Concat operator is used to concatenate two sequences into one sequence without removing the
duplicate elements. That means it simply returns the elements from the first sequence followed by the
elements from the second sequence. On the other hand, the LINQ Union operator is also used to
concatenate two sequences into one sequence by removing duplicate elements. For a better
understanding, please have a look at the following example where we are using both Cancat and
Union Methods on the same data sources.
using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
class Program
{
static void Main(string[] args)
{
//Data Sources
List<int> sequence1 = new List<int> { 1, 2, 3, 4 };
List<int> sequence2 = new List<int> { 2, 4, 6, 8 };
Console.ReadLine();
}
}
}
Output:
As you can see in the above output, the Concat method returns the duplicate elements whereas the
Union method removes the duplicate elements from the result set.