- Reference
Definition
- Namespace:
- System.Linq
- Assembly:
- System.Linq.dll
- Assembly:
- System.Core.dll
- Assembly:
- netstandard.dll
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Returns distinct elements from a sequence.
Overloads
Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) | Returns distinct elements from a sequence by using a specified IEqualityComparer<T> to compare values. |
Distinct<TSource>(IEnumerable<TSource>) | Returns distinct elements from a sequence by using the default equality comparer to compare values. |
Remarks
The result sequence is unordered.
Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)
Returns distinct elements from a sequence by using a specified IEqualityComparer<T> to compare values.
public:generic <typename TSource>[System::Runtime::CompilerServices::Extension] static System::Collections::Generic::IEnumerable<TSource> ^ Distinct(System::Collections::Generic::IEnumerable<TSource> ^ source, System::Collections::Generic::IEqualityComparer<TSource> ^ comparer);
public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, System.Collections.Generic.IEqualityComparer<TSource> comparer);
public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>? comparer);
static member Distinct : seq<'Source> * System.Collections.Generic.IEqualityComparer<'Source> -> seq<'Source>
<Extension()>Public Function Distinct(Of TSource) (source As IEnumerable(Of TSource), comparer As IEqualityComparer(Of TSource)) As IEnumerable(Of TSource)
Type Parameters
- TSource
The type of the elements of source
.
Parameters
- source
- IEnumerable<TSource>
The sequence to remove duplicate elements from.
- comparer
- IEqualityComparer<TSource>
An IEqualityComparer<T> to compare values.
Returns
- IEnumerable<TSource>
An IEnumerable<T> that contains distinct elements from the source sequence.
Exceptions
ArgumentNullException
source
is null
.
Examples
The following example shows how to implement an equality comparer that can be used in the Distinct method.
public class Product{ public string Name { get; set; } public int Code { get; set; }}// Custom comparer for the Product classclass ProductComparer : IEqualityComparer<Product>{ // Products are equal if their names and product numbers are equal. public bool Equals(Product x, Product y) { //Check whether the compared objects reference the same data. if (Object.ReferenceEquals(x, y)) return true; //Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; //Check whether the products' properties are equal. return x.Code == y.Code && x.Name == y.Name; } // If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects. public int GetHashCode(Product product) { //Check whether the object is null if (Object.ReferenceEquals(product, null)) return 0; //Get hash code for the Name field if it is not null. int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode(); //Get hash code for the Code field. int hashProductCode = product.Code.GetHashCode(); //Calculate the hash code for the product. return hashProductName ^ hashProductCode; }}
Public Class Product Public Property Name As String Public Property Code As IntegerEnd Class' Custom comparer for the Product classPublic Class ProductComparer Implements IEqualityComparer(Of Product) Public Function Equals1( ByVal x As Product, ByVal y As Product ) As Boolean Implements IEqualityComparer(Of Product).Equals ' Check whether the compared objects reference the same data. If x Is y Then Return True 'Check whether any of the compared objects is null. If x Is Nothing OrElse y Is Nothing Then Return False ' Check whether the products' properties are equal. Return (x.Code = y.Code) AndAlso (x.Name = y.Name) End Function Public Function GetHashCode1( ByVal product As Product ) As Integer Implements IEqualityComparer(Of Product).GetHashCode ' Check whether the object is null. If product Is Nothing Then Return 0 ' Get hash code for the Name field if it is not null. Dim hashProductName = If(product.Name Is Nothing, 0, product.Name.GetHashCode()) ' Get hash code for the Code field. Dim hashProductCode = product.Code.GetHashCode() ' Calculate the hash code for the product. Return hashProductName Xor hashProductCode End FunctionEnd Class
After you implement this comparer, you can use a sequence of Product
objects in the Distinct method, as shown in the following example:
Product[] products = { new Product { Name = "apple", Code = 9 }, new Product { Name = "orange", Code = 4 }, new Product { Name = "apple", Code = 9 }, new Product { Name = "lemon", Code = 12 } };// Exclude duplicates.IEnumerable<Product> noduplicates = products.Distinct(new ProductComparer());foreach (var product in noduplicates) Console.WriteLine(product.Name + " " + product.Code);/* This code produces the following output: apple 9 orange 4 lemon 12*/
Dim products() As Product = {New Product With {.Name = "apple", .Code = 9}, New Product With {.Name = "orange", .Code = 4}, New Product With {.Name = "apple", .Code = 9}, New Product With {.Name = "lemon", .Code = 12}}' Exclude duplicates.Dim noduplicates = products.Distinct(New ProductComparer())For Each product In noduplicates Console.WriteLine(product.Name & " " & product.Code)Next' This code produces the following output:'' apple 9' orange 4' lemon 12'
Remarks
This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
The Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) method returns an unordered sequence that contains no duplicate values. If comparer
is null
, the default equality comparer, Default, is used to compare values.
Applies to
Distinct<TSource>(IEnumerable<TSource>)
Returns distinct elements from a sequence by using the default equality comparer to compare values.
public:generic <typename TSource>[System::Runtime::CompilerServices::Extension] static System::Collections::Generic::IEnumerable<TSource> ^ Distinct(System::Collections::Generic::IEnumerable<TSource> ^ source);
public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);
static member Distinct : seq<'Source> -> seq<'Source>
<Extension()>Public Function Distinct(Of TSource) (source As IEnumerable(Of TSource)) As IEnumerable(Of TSource)
Type Parameters
- TSource
The type of the elements of source
.
Parameters
- source
- IEnumerable<TSource>
The sequence to remove duplicate elements from.
Returns
- IEnumerable<TSource>
An IEnumerable<T> that contains distinct elements from the source sequence.
Exceptions
ArgumentNullException
source
is null
.
Examples
The following code example demonstrates how to use Distinct<TSource>(IEnumerable<TSource>) to return distinct elements from a sequence of integers.
List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };IEnumerable<int> distinctAges = ages.Distinct();Console.WriteLine("Distinct ages:");foreach (int age in distinctAges){ Console.WriteLine(age);}/* This code produces the following output: Distinct ages: 21 46 55 17*/
' Create a list of integers.Dim ages As New List(Of Integer)(New Integer() _ {21, 46, 46, 55, 17, 21, 55, 55})' Select the unique numbers in the List.Dim distinctAges As IEnumerable(Of Integer) = ages.Distinct()Dim output As New System.Text.StringBuilder("Distinct ages:" & vbCrLf)For Each age As Integer In distinctAges output.AppendLine(age)Next' Display the output.Console.WriteLine(output.ToString)' This code produces the following output:'' Distinct ages:' 21' 46' 55' 17
If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable<T> generic interface in the class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.
public class MyProduct : IEquatable<MyProduct>{ public string Name { get; set; } public int Code { get; set; } public bool Equals(MyProduct other) { //Check whether the compared object is null. if (Object.ReferenceEquals(other, null)) return false; //Check whether the compared object references the same data. if (Object.ReferenceEquals(this, other)) return true; //Check whether the products' properties are equal. return Code.Equals(other.Code) && Name.Equals(other.Name); } // If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects. public override int GetHashCode() { //Get hash code for the Name field if it is not null. int hashProductName = Name == null ? 0 : Name.GetHashCode(); //Get hash code for the Code field. int hashProductCode = Code.GetHashCode(); //Calculate the hash code for the product. return hashProductName ^ hashProductCode; }}
Public Class Product Implements IEquatable(Of Product) Public Property Name As String Public Property Code As Integer Public Function Equals1( ByVal other As Product ) As Boolean Implements IEquatable(Of Product).Equals ' Check whether the compared object is null. If other Is Nothing Then Return False ' Check whether the compared object references the same data. If Me Is Other Then Return True ' Check whether the products' properties are equal. Return Code.Equals(other.Code) AndAlso Name.Equals(other.Name) End Function Public Overrides Function GetHashCode() As Integer ' Get hash code for the Name field if it is not null. Dim hashProductName = If(Name Is Nothing, 0, Name.GetHashCode()) ' Get hash code for the Code field. Dim hashProductCode = Code.GetHashCode() ' Calculate the hash code for the product. Return hashProductName Xor hashProductCode End FunctionEnd Class
After you implement this interface, you can use a sequence of Product
objects in the Distinct<TSource>(IEnumerable<TSource>) method, as shown in the following example:
MyProduct[] products = { new MyProduct { Name = "apple", Code = 9 }, new MyProduct { Name = "orange", Code = 4 }, new MyProduct { Name = "apple", Code = 9 }, new MyProduct { Name = "lemon", Code = 12 } };// Exclude duplicates.IEnumerable<MyProduct> noduplicates = products.Distinct();foreach (var product in noduplicates) Console.WriteLine(product.Name + " " + product.Code);/* This code produces the following output: apple 9 orange 4 lemon 12*/
Dim products() As Product = {New Product With {.Name = "apple", .Code = 9}, New Product With {.Name = "orange", .Code = 4}, New Product With {.Name = "apple", .Code = 9}, New Product With {.Name = "lemon", .Code = 12}}' Exclude duplicates.Dim noduplicates = products.Distinct()For Each product In noduplicates Console.WriteLine(product.Name & " " & product.Code)Next' This code produces the following output:'' apple 9' orange 4' lemon 12'
Remarks
This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator
method directly or by using foreach
in Visual C# or For Each
in Visual Basic.
The Distinct<TSource>(IEnumerable<TSource>) method returns an unordered sequence that contains no duplicate values. It uses the default equality comparer, Default, to compare values.
In Visual Basic query expression syntax, a Distinct
clause translates to an invocation of Distinct.
The default equality comparer, Default, is used to compare values of the types that implement the IEquatable<T> generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.
For an example that uses IEqualityComparer<T> to define a custom comparer, see Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>).
See also
- Distinct Clause (Visual Basic)
Applies to
FAQs
How to get distinct records in Linq C#? ›
- public JsonResult getEmpCity()
- {
- using (CompanyDBEntities dc = new CompanyDBEntities())
- {
- var query = (from p in dc. Emp_Information.
- select p. City). ToList();
- return new JsonResult.
- {
First, you need to get the partial strings. Then You reduce the resulting collections to one. Then split the individual strings by "=" and select only those that have "B" as first value and not "TestA" as second. Then select the second value and call Distinct , which removes duplicate values.
What is Linq enumerable? ›Count Method (System. Linq) Returns the number of elements in a sequence.
How to get distinct values from array in C#? ›To remove duplicate values and get distinct values from an object array, we need to implement either IEquatable or IEqualityComparer . The following example gets a distinct array of the Person array. The following class implements IEqualityComparer<T> to be used with the Distinct() method.
How to get distinct elements in LINQ? ›If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable<T> generic interface in the class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.
What is the difference between distinct and group by LINQ? ›DISTINCT is used to filter unique records out of the records that satisfy the query criteria. The "GROUP BY" clause is used when you need to group the data and it should be used to apply aggregate operators to each group.
How do I filter distinct data? ›To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates. To highlight unique or duplicate values, use the Conditional Formatting command in the Style group on the Home tab.
How to get distinct values from two list in C#? ›var differences = list1. Except(list2); And then you can loop through the differences: foreach(var difference in differences) { // work with each individual string here. }
How can you find distinct elements in an array using stream? ›distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.
What is an enumerable method? ›Enumeration refers to traversing over objects. In Ruby, we call an object enumerable when it describes a set of items and a method to loop over each of them.
What is the difference between enumerable and Queryable? ›
The main difference between IEnumerable and IQueryable in C# is that IQueryable queries out-of-memory data stores, while IEnumerable queries in-memory data. Moreover, IQueryable is part of . NET's System.
What is the use of enumerable in C#? ›IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
How do you check if all elements in an array are distinct? ›One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return True. If no element repeats, return false.
How do I find distinct data? ›The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
How do I find distinct elements in two arrays? ›- Create an empty array that would store the unique elements from the two arrays.
- Iterate over all elements of array1 using a loop.
- Set the initial flag value as 0 for each iteration.
- In that loop Iterate over all elements of array2 using another loop and check if array1[element] is present in array2.
A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignores the element, else prints the element.
How do you find the distinct value of a string? ›...
- Use Counter to get the container.
- Use keys() method to get unique values.
- Use most_common() method to get the unique values and frequency.
- Initialize a Set, say DistString, to store the distinct strings from the given array.
- Traverse the array and insert array elements into DistString.
- Finally, print all strings from DistString.
However, in more complex cases, DISTINCT can end up doing more work. Essentially, DISTINCT collects all of the rows, including any expressions that need to be evaluated, and then tosses out duplicates. GROUP BY can (again, in some cases) filter out the duplicate rows before performing any of that work.
Which is faster distinct or GROUP BY? ›GROUP BY is slightly faster than SELECT DISTINCT
The difference is hardly noticeable to users. These tests were done on Access back-end database tables and may not hold for other types of data sources (e.g., SQL Server linked tables)
Should we use distinct or GROUP BY? ›
The major difference between the DISTINCT and GROUP BY is, GROUP BY operator is meant for the aggregating or grouping rows whereas DISTINCT is just used to get distinct values.
How does Linq distinct work? ›C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).
How do you remove duplicates from data without using distinct? ›- Remove Duplicates Using Row_Number. WITH CTE (Col1, Col2, Col3, DuplicateCount) AS ( SELECT Col1, Col2, Col3, ROW_NUMBER() OVER(PARTITION BY Col1, Col2, Col3 ORDER BY Col1) AS DuplicateCount FROM MyTable ) SELECT * from CTE Where DuplicateCount = 1.
- Remove Duplicates using group By.
“Distinct” means total number of different values regardless how many times it appears in the dataset. A name appears in the list multiple times is counted as 1 distinct count. Whereas, the “Unique” value is total number of values that only appear once.
Can we use distinct on 2 columns? ›We can use the DISTINCT clause on more than columns in MySQL. In this case, the uniqueness of rows in the result set would depend on the combination of all columns.
Can I use distinct twice? ›You can use DISTINCT on multiple columns. The DISTINCT keyword applies to the entire result set, so adding DISTINCT to your query with multiple columns will find unique results. This query also shows 6 results because there are 6 unique records.
How do I get unique records from a list? ›- Python set() method.
- Using Python list. append() method along with a for loop.
- Using Python numpy. unique() method.
The Flajolet–Martin algorithm is an algorithm for approximating the number of distinct elements in a stream with a single pass and space-consumption logarithmic in the maximal number of possible distinct elements in the stream (the count-distinct problem).
How do you use distinct aggregate functions? ›You can use the optional keyword distinct only with sum, avg, count_big, and count.
How do I find the distinct value of a object? ›One way to get distinct values from an array of JavaScript objects is to use the array's map method to get an array with the values of a property in each object. Then we can remove the duplicate values with the Set constructor. And then we can convert the set back to an array with the spread operator.
How to get distinct rows from DataTable in C#? ›
- first parameter in ToTable() is a boolean which indicates whether you want distinct rows or not.
- second parameter in the ToTable() is the column name based on which we have to select distinct rows. Only these columns will be in the returned datatable.
The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to: var query = lst. GroupBy(x => x) .
How to get distinct rows from DataTable in UiPath? ›- Step1: Drag and drop a Build data table Activity and create a DataTable as shown below:
- Step2: Drag and drop an Assign activity and write the command there as shown below:
- Let's discuss about the command that we wrote there:
- In this (true,”Name”) -(Boolean,Column Name)
In C#, LINQ is present in System. Linq namespace. It provides different type of classes and methods which supports LINQ queries.
How do I select distinct values from a dataset? ›Get distinct Product from this Dataset, DataTable distinctDT = SelectDistinct(dsOrders. Tables[0], "Product");
How to remove duplicate rows from dataset in C#? ›- Remember, the pain of removing duplicates in fetched dataset by looping, comparing etc. it can be handled easily by using DataView. ...
- DataTable temp = dt.DefaultView.ToTable(true, "Region"); Ex2.
- DataTable temp = dt.DefaultView.ToTable(true, "Region", "City"); Reference:
You can use ToTable(distinct As Boolean, ParamArray columnNames As String()) method for this. This will return distinct Users for you. You can add multiple column names if you want. Please edit with more information.
What is the easiest way to find duplicate files? ›- CCleaner.
- Easy Duplicate File Finder.
- SearchMyFiles.
- XYplorer.
- Duplicate Sweeper.
- Wise Duplicate Finder.
- CloneSpy.
- Fast Duplicate File Finder.
We can remove all duplicates like this by using GroupBy and Select methods provided by LINQ . First, we group our list so that we will create groups for each name in the List. Then we use Select to only select the first objects in each group. This will result in the removal of the duplicates.
Is it a good idea to maintain duplicate records? ›It is a good idea to maintain duplicate records in different locations for ease of access. Penalties for unlawful or accidental removal, defacing, alteration, or destruction of Federal records or the attempt to do so, include a fine, imprisonment, or both.
How do I get distinct values from all columns? ›
To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.
How do you find total distinct records? ›We can use SQL Count Function to return the number of rows in the specified condition. The syntax of the SQL COUNT function: COUNT ([ALL | DISTINCT] expression); By default, SQL Server Count Function uses All keyword.
Is LINQ faster than for loop? ›LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.
Why use LINQ instead of SQL? ›Compared to SQL, LINQ is simpler, tidier, and higher-level. It's rather like comparing C# to C++. Sure, there are times when it's still best to use C++ (as is the case with SQL), but in most situations, working in a modern tidy language and not having to worry about lower-level details is a big win.
What is the main purpose of LINQ in C#? ›Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.