[LINQ Operators] Distinct

The “Distinct” operator eliminates duplicate elements from a sequence. You can provide the custom comparison logic as an “IEqualityComparer<T>” object.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “Distinct” operator

  • Deferred operator
  • Purpose: Set

 

3. Prototypes

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

public static IEnumerable<T> Distinct<T>
(this IEnumerable<T> source, IEqualityComparer<T> comparer)

The “Distinct()” operator returns distinct elements as a sequence. You can provide your own comparer “IEqualityComparer<T>“.

 

4. Example 1 (Standard Operator)

int[] numbers = {1,2,3,4,5,4,3,2,1};

var distinctNumbers = numbers.Distinct();
foreach (var num in distinctNumbers)
{
  Console.WriteLine($"{num}");
}

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “Distinct()” operator.

 

6. Example 3 (Standard Operator) – with a custom comparer

public class MyNumberEquality : IEqualityComparer<int>
{
  public bool Equals(int x, int y)
  {
    return (x % 10 == y % 10);
  }
  public int GetHashCode(int obj)
  {
    return (obj % 10).GetHashCode();
  }
}

 

int[] numbers = { 11, 12, 13, 21, 22, 23, 24, 31, 32, 33, 34, 35 };

var comparer = new MyNumberEquality();

var distinctNumbers = numbers.Distinct(comparer);
foreach (var num in distinctNumbers)
{
  Console.WriteLine($"{num}");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s