📜  LINQ |设置运算符|联盟(1)

📅  最后修改于: 2023-12-03 14:43:54.391000             🧑  作者: Mango

LINQ | Set Operators | Union

LINQ (Language Integrated Query) is a powerful tool for querying data in .NET languages. One of its features is the ability to perform set operations like Union, Intersection and Except on collections of data.

In this post, we will focus on the Union operator, which is used to combine two collections into a single collection containing all distinct elements from both collections.

Syntax

The Union operator can be used in the following syntax:

var unionList = list1.Union(list2);

Here, list1 and list2 are two collections of the same data type. The Union operator returns a new collection that contains all the distinct elements from both list1 and list2.

Example

Let's consider the following example:

int[] list1 = { 1, 2, 3, 4, 5 };
int[] list2 = { 3, 4, 5, 6, 7 };

var unionList = list1.Union(list2);

In this example, we have two integer arrays, list1 and list2. We use the Union operator to combine the two arrays into a single array unionList, which contains all the distinct elements from both arrays.

The resulting unionList will contain the elements { 1, 2, 3, 4, 5, 6, 7 }.

Important Points
  • The Union operator returns a new collection and does not modify the original collections.
  • The resulting collection contains only distinct elements from both collections. If there are duplicates in the original collections, only one copy will be included in the resulting collection.
  • The Union operator works only on collections of the same data type.
  • The Union operator can be expensive in terms of performance, especially on large collections, because it has to check each element in both collections for duplicates. Consider using other set operators like Concat or Distinct depending on your use case.

That's it! The Union operator is a powerful tool for combining and de-duplicating collections of data. Try it out in your own code and see the benefits of LINQ for yourself.