Skip to main content

There are a number of useful LINQ set-based operations that are often overlooked.

``````---
title: Useful LINQ Set Operations
subtitle: There are a number of useful LINQ set-based operations that are often overlooked.
author: C# Tips
date: May 16, 2022
source: https://leanpub.com/cstips
snippet: https://jonlabelle.com/snippets/view/markdown/useful-linq-set-operations
notoc: false
---

## Concat

To join two IEnumerable sequences together:

```csharp
IEnumerable<int>oneToFive=new[]{1,2,3,4,5};
IEnumerable<int>sixToTen=new[]{6,7,8,9,10};

IEnumerable<int>oneToTen=oneToFive.Concat(sixToTen);
```

oneTen now contains the values 1 through 10;

## Union

To combine all the unique values:

```csharp
IEnumerable<int>oneToFive=new[]{1,2,3,4,5};
IEnumerable<int>twoToSix=new[]{2,3,4,5,6};

IEnumerable<int>oneToSix=oneToFive.Union(twoToSix);
```

oneToSix now contains 1 through 6. The values 2, 3, 4, 5 are not duplicated in the result.

## Intersect

To get values that only appear in both sequences:

```csharp
IEnumerable<int>oneToFive=new[]{1,2,3,4,5};
IEnumerable<int>twoToSix=new[]{2,3,4,5,6};

IEnumerable<int>twoToFive=oneToFive.Intersect(twoToSix);
```

twoToFive contains only 2 through 5. 1 and 6 do not appear as they do not appear in both sequences.

## Except

To get only those values inside the first sequence that do not appear in the second sequence:

```csharp
IEnumerable<int>oneToFive=new[]{1,2,3,4,5};
IEnumerable<int>sixToTen=new[]{6,7,8,9,10};

IEnumerable<int>resultOneToFive=oneToFive.Except(sixToTen);
```

resultOneToFive contains all the values from the first sequence as none of them appear in the second sequence sixToTen.

As another example:

```csharp
varcolors=new[]{"Red","Green","Blue"};

varcolorsResult=colors.Except(new[]{"Red","Green","Orange"});
```

colorsResult contains only "Blue" because "Blue" does not appear in the second sequence "Red", "Green", "Orange".
``````