CSharp - LINQ Distinct


The Distinct operator removes duplicate elements from an input sequence.


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.


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.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from  w w  w  .j a v a2 s  .c  o m
    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());