C# Distinct Method: Remove Duplicates

In C#, you can use the Distinct method of LINQ (Language Integrated Query) to retrieve unique elements from a collection. The Distinct method removes duplicate elements in the collection, keeping only one unique instance of each element.

Here is a simple example demonstrating how to use the Distinct method:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };

        var distinctNumbers = numbers.Distinct();

        foreach (var number in distinctNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

In the example above, we first created a list of integers containing duplicate elements. Then we used the Distinct method to retrieve unique elements and output them to the console. The output result is:

1
2
3
4
5
bannerAds