Set Operators in LINQ using C#
In this article, I am going to discuss Set Operators in LINQ using C#. Please read our previous article where we discussed OfType operators in LINQ with some examples. As part of this article, we are going to discuss the following concepts.
Note: The most important thing that we always need to remember is, before learning something first we need to understand where and why we need to use that thing. With this keep in mind let’s proceed to this article.
Set Operators in LINQ:
The Set Operators in LINQ are used to produce the result set based on the presence and absence of elements within the same or different data sources. That means these operations are performed either on a single data source or on multiple data sources and in the output some of the data are present and some of the data are absent. If this is not clear at the moment then don’t worry we will discuss each and everything with examples.
Examples of Set Operations:
Let us discuss some of the examples where we need to use the set operations.
- If we need to select the distinct records from a data source (No Duplicate Records) then we need to use Set Operators.
- Suppose we need to select all the Employees of a company except a particular department then you need to use Set Operations.
- Another example maybe if you have multiple classes and you want only to select all the toppers from all the classes then also you need to use Set Operations.
- Suppose we have different data sources with similar structure and if we want to combine all the data sources into a single data source then we need to use Set Operations.
LINQ Set Operation Methods in C#:
The following LINQ Extension Methods are provided to perform set operations in C#.
Distinct: We need to use the Distinct() method when we want to remove the duplicate data or records from a data source. This method operates on a single data source.
Except: We need to use the Except() LINQ Extension method when we want to return all the elements from the first data source which do not exists in the second data source. This method operates on two data sources.
Intersect: This method is used to return the common elements from both the data sources i.e. the elements which exist in both the data set are going to returns as output.
Union: This method is used to return all the elements which are present in either of the data sources. That means it combines the data from both the data sources and produce a single result set.
In the next article, I am going to discuss the LINQ Distinct Method in C# with examples. In this article, I try to explain the need for Set Operators and the different types of set operators provided by linq.