[LINQ Operators] Union

The “Union” operator produces the set union of two sequences. You can provide the custom comparer “IEqualityComparer<T>”.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “Union” operator

  • Deferred operator
  • Purpose: Set

 

3. Prototypes

public static IEnumerable<T> Union<T>(
  this IEnumerable<T> first,
  IEnumerable<T> second)

public static IEnumerable<T> Union<T>(
  this IEnumerable<T> first,
  IEnumerable<T> second,
  IEqualityComparer<T> comparer)

The “Union()” operator produces the set union of two sequences by using the default equality comparer or the custom comparer.

 

4. Example 1 (Standard Operator)

int[] numbers1 = {1,2,3,4,5};
int[] numbers2 = {7,6,5,4,3};

var unionNumbers = numbers1.Union(numbers2);
foreach (var num in unionNumbers)
{
  Console.WriteLine($"{num}"); // 1,2,3,4,5,7,6
}

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “Union()” operator.

 

6. Example 3 (Standard Operator) – with a custom comparer

public class MyNumberEquality : IEqualityComparer<int>
{
  public bool Equals(int x, int y)
  {
    return (x % 10 == y % 10);
  }
  public int GetHashCode(int obj)
  {
    return (obj % 10).GetHashCode();
  }
}

 

int[] numbers1 = {11,12,13,21,22,23,24,31,32,33,34,35};
int[] numbers2 = {13,14,24,25,35,36,45,46,47};

MyNumberEquality comparer = new MyNumberEquality();
var unionNumbers = numbers1.Union(numbers2, comparer);

foreach (var num in unionNumbers)
{
  Console.WriteLine($"{num}"); // 11,12,13,24,35,36,47
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s