typestar

Set operations in C#

Intersect, Except and Union treat sequences as sets.

var deployed = new[] { "auth", "api", "worker", "cron" };
var healthy = new[] { "api", "auth", "metrics" };

Console.WriteLine(string.Join(",", deployed.Intersect(healthy)));
Console.WriteLine(string.Join(",", deployed.Except(healthy)));
Console.WriteLine(string.Join(",", deployed.Union(healthy)));

// order matters to sequences, never to sets
Console.WriteLine(deployed.SequenceEqual(healthy));
Console.WriteLine(new[] { 1, 2 }.SequenceEqual(new[] { 1, 2 }));

How it works

  1. Intersect is what both sides share; Except is the difference.
  2. Union merges and deduplicates in one pass.
  3. SequenceEqual is the order-sensitive comparison, for contrast.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
462
Tokens
126
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 2 of 3 in Materializing & sets, step 14 of 17 in LINQ in depth.

← Previous Next →

Set operations in other languages