CSharp - LINQ Distinct

Introduction

The Distinct operator removes duplicate elements from an input sequence.

Prototypes

public static IEnumerable<T> Distinct<T>(
  this IEnumerable<T> source);

An element is determined to be equal to another element using their GetHashCode and Equals methods.

Exceptions

ArgumentNullException is thrown if the source argument is null.

For this example, we are going to first display the count of the codeNames array.

Then we will concatenate the codeNames array with itself, display the count of the resulting concatenated sequence.

Then call the Distinct operator on that concatenated sequence, and finally display the count of the distinct sequence.

To determine the count of the two generated sequences, we will use the Count Standard Query Operator.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from   w w w  .  j a va 2  s . com*/
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};

        //  Display the count of the codeNames array.
        Console.WriteLine("codeNames count:  " + codeNames.Count());

        //  Concatenate codeNames with itself.  Now each element should
        //  be in the sequence twice.
        IEnumerable<string> codeNamesWithDupes = codeNames.Concat(codeNames);
        //  Display the count of the concatenated sequence.
        Console.WriteLine("codeNamesWithDupes count:  " + codeNamesWithDupes.Count());

        //  Eliminate the duplicates and display the count.
        IEnumerable<string> codeNamesDistinct = codeNamesWithDupes.Distinct();
        Console.WriteLine("codeNamesDistinct count:  " + codeNamesDistinct.Count());
    }
}

Result