C# Enumerable Distinct(IEnumerable)

Description

Returns distinct elements from a sequence by using the default equality comparer to compare values.

Syntax


public static IEnumerable<TSource> Distinct<TSource>(
  this IEnumerable<TSource> source
)

Parameters

  • TSource - The type of the elements of source.
  • source - The sequence to remove duplicate elements from.

Returns

Returns distinct elements from a sequence by using the default equality comparer to compare values.

Example

The following code example demonstrates how to use Distinct(IEnumerable) to return distinct elements from a sequence of integers.


/*w  w  w.  j  a  v  a2  s.com*/

using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
    List<int> ages = new List<int> { 2, 4, 4, 5};
    IEnumerable<int> distinctAges = ages.Distinct();
    Console.WriteLine("Distinct ages:");
    foreach (int age in distinctAges){
       Console.WriteLine(age);
    }

  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable