---
title: "Distinct() with lambda, can you explain?"  
description: "Distinct() with lambda, can you explain?"  
author: "Steilla Mitchel"  
published: 2023-08-17  
updated: 2023-08-18  
canonical: https://www.mindstick.com/forum/159551/distinct-with-lambda-can-you-explain  
category: "c#"  
tags: ["c#", "linq", "lambda expression"]  
reading_time: 2 minutes  

---

# Distinct() with lambda, can you explain?

[Distinct](https://www.mindstick.com/forum/159558/why-c-sharp-linq-distinct-doesn-t-work)() with [lambda](https://www.mindstick.com/blog/181/lambda-expression-in-c-sharp), can you [explain](https://www.mindstick.com/forum/157854/what-is-system-debugging-explain-some-system-debugging-tools-used-in-modern-computer-systems)?

## Replies

### Reply by Aryan Kumar

Sure. The `distinct()` method in C++ can be used to remove duplicate elements from a sequence. The `distinct()` method takes an optional parameter that specifies the comparer to use when comparing elements. If the parameter is 0, the default comparer is used. The default comparer compares elements by their GetHashCode() method.

Lambda expressions can be used to provide a custom comparer to the `distinct()` method. The following code is an example of how to use a lambda expression with the `distinct()` method:

C++

```plaintext
#include <iostream>
#include <vector>

using namespace std;

int main() {
  vector<int> numbers = {1, 2, 3, 2, 1};

  // Use a lambda expression to define a custom comparer.
  auto comparer = [](int x, int y) { return x < y; };

  // Remove the duplicates from the vector.
  numbers = numbers.distinct(comparer);

  // Print the elements of the vector.
  for (int number : numbers) {
    cout << number << " ";
  }

  cout << endl;

  return 0;
}
```

In this code, the `comparer` lambda expression defines a custom comparer that compares two integers and returns a value indicating whether the first integer is less than the second integer. The `distinct()` method uses the `comparer` lambda expression to remove the duplicates from the `numbers` vector.


---

Original Source: https://www.mindstick.com/forum/159551/distinct-with-lambda-can-you-explain

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
