0
0
C Sharp (C#)programming~5 mins

Set operations (Union, Intersect, Except) in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Set operations help you combine or compare groups of items easily. They let you find common items, all items, or items only in one group.

You want to find all unique friends from two friend lists.
You want to see which products appear in both your store and a competitor's store.
You want to remove items from a list that are already sold.
You want to find items that are only in one list but not the other.
Syntax
C Sharp (C#)
var union = set1.Union(set2);
var intersect = set1.Intersect(set2);
var except = set1.Except(set2);

These methods return a new collection without changing the original sets.

They work on any collections that implement IEnumerable<T>.

Examples
Union combines all unique numbers from both lists: 1, 2, 3, 4, 5.
C Sharp (C#)
var set1 = new List<int> {1, 2, 3};
var set2 = new List<int> {3, 4, 5};
var union = set1.Union(set2);
Intersect finds numbers common to both lists: 3.
C Sharp (C#)
var intersect = set1.Intersect(set2);
Except finds numbers in set1 but not in set2: 1, 2.
C Sharp (C#)
var except = set1.Except(set2);
Sample Program

This program shows how to use Union, Intersect, and Except with two lists of fruits.

C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var set1 = new List<string> {"apple", "banana", "cherry"};
        var set2 = new List<string> {"banana", "date", "fig"};

        var union = set1.Union(set2);
        var intersect = set1.Intersect(set2);
        var except = set1.Except(set2);

        Console.WriteLine("Union: " + string.Join(", ", union));
        Console.WriteLine("Intersect: " + string.Join(", ", intersect));
        Console.WriteLine("Except: " + string.Join(", ", except));
    }
}
OutputSuccess
Important Notes

Set operations do not change the original lists; they create new results.

Order of items in the result may not be guaranteed.

Use these operations to simplify comparing and combining collections.

Summary

Union combines all unique items from two collections.

Intersect finds items common to both collections.

Except finds items in the first collection but not in the second.