In this article, I am going to discuss the Linq Concat Method in C# with some examples. Please read our previous article before proceeding to this article where we discussed the Linq Union Method in C# with some examples. As part of this article, we are going to discuss the following pointers. What is the Concat Method in Linq?
- What is the Concat Method in Linq?
- Why do we need to use the Concat Method?
- Examples using both Query and Method Syntax.
- What are the differences between Concat and union operators in Linq?
Linq Concat Method in C#:
The Linq Concat Method in C# is used to concatenate two sequences into one sequence. There is only one version available for this method whose signature is given below.
Example1:
In the following example, we have created two integer sequences and then concatenate two sequences into one sequence using the Concat operator.
Output:
If you notice in the above output then you will see that the duplicate elements are not removed. Now let us concatenate the above two sequences using the Union operator and observe what happened.
Concatenate using Union Operator:
In the below example, we concatenate the two integer sequences into one sequence using the Linq Union Operator.
Output:
If you observe in the above output, then you will see that the duplicate elements are removed from the result set.
What is the difference between Concat and Union operators in Linq?
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 the duplicate elements.
Note: While working with the Concat operator if any of the sequences is null then it will throw an exception.
Example2:
In the following example, the second sequence is null and while performing the concatenate operation using the concat operator it will throw an exception.
Now run the application and you will get the following exception.