Updated April 7, 2023
Definition of LINQ Distinct
LINQ Distinct is an operator which comes under Set Operator. Distinct method returns the unique values from the collection of list; it returns the new set of unique elements from the given collection.The distinct operator removes all the duplicate values from the collection and finally returns the dissimilar or unique values. The LINQ Distinct operator available in only Method Syntax and it not supports the Query Syntax.
Syntax:
The LINQ Distinct operator syntax as follows below,
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source);
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);
It contains two overloaded methods in which the first type does not contain any parameter and the second one contains the IEqualityComparer parameter to check the complex types.
How Distinct Works in LINQ?
LINQ Distinct operator removes all the duplicate values from the collection and finally returns the dissimilar or unique values. The LINQ Distinct operator available in only Method Syntax and it not supports the Query Syntax. LINQ Distinct is an operator which comes under Set Operator.
For Example,
Let’s assume one set of collection, List= {2, 3, 5, 5, 7, 8, 7, 9, 9} In this collection of values 5, 7, 9 are repeated twice in the collection so we need to eliminate the duplications and return the result for that we need to use the distinct operator in the collection. The distinct method returns the unique values from the collection of list.
Result= List. distinct ();
Result= {2, 3, 5, 7, 8, 9};
The distinct method returns the unique values from the collection of list; it returns the new set of unique elements from the given collection. Let’s see the below program,
Code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDistinct_
{
class ProgramSample
{
static void Main(string[] args)
{
List<int>listValues = new List<int>()
{
70,30,40,20,30,40,70,50,60,30,40,50
};
Console.WriteLine("BASIC LINQ DISTINCT EXAMPLE\n");
//use of method_syntax type
varmethod_type = listValues.Distinct();
//use of query_syntax type
varquery_type = (from num in listValues
select num).Distinct();
Console.WriteLine("LINQ DISTINCT- Method_Type\n");
foreach (var result in method_type)
{
Console.WriteLine(result);
}
Console.WriteLine("LINQ DISTINCT- Query_Type\n");
foreach (var result in query_type)
{
Console.WriteLine(result);
}
Console.ReadKey();
}
}
}
In this program, it retrieves the distinct values using query type and method type. In method type is get the values in the list of collection asList<int>listValuesand it use the distinct function type asvarmethod_type = listValues.Distinct();finally it returns the result as non-duplication values. In query type as same as it get values in list of collection in List<int>listValuesand it use distinct by query type as follows,
varquery_type = (from num in listValues select num).Distinct();
Output:
Examples of LINQ Distinct
The distinct operator removes all the duplicate values from the collection and finally returns the dissimilar or unique values. The LINQ Distinct operator available in only Method Syntax and it not supports the Query Syntax. Let’s see the following examples programmatically,
Example #1
In this program the string collection contains courses with repeated names as follows,string[] Courses = { “JAVA”, “DOTNET”, “PHP”, “ANDROID”, “JAVA”, “PHYTHOD”,”ANDROID”, “ANDROID” }, by using distinct operator we can get new collection of elements without duplications.
Code:
using System;
using System.Linq;
using System.Collections.Generic;
class LinqDistinct_class
{
// in main-method
static public void Main()
{
string[] Courses = { "JAVA", "DOTNET", "PHP", "ANDROID", "JAVA", "PHYTHOD", "ANDROID", "ANDROID" };
vardistinctCourses = Courses.Distinct();
Console.WriteLine("Distinct Method - Unique Courses\n");
foreach (varcName in distinctCourses)
{
Console.WriteLine(cName);
}
Console.ReadLine();
}
}
Output:
Example #2
Code:
using System;
using System.Linq;
using System.Collections.Generic;
// Employee Basic Details
public class EmployeeClass
{
public intemployee_id
{
get;
set;
}
public string employee_name
{
get;
set;
}
public string employee_gender
{
get;
set;
}
public string employee_JoiningDate
{
get;
set;
}
public intemployee_salary
{
get;
set;
}
}
class LinqDistinct_class
{
// in main-method
static public void Main()
{
List<EmployeeClass>employeeList = new List<EmployeeClass>() {
new EmployeeClass() {employee_id = 1001, employee_name = "Sasha", employee_gender = "Female",
employee_JoiningDate = "18/7/2015", employee_salary = 45000},
new EmployeeClass() {employee_id = 1002, employee_name = "Sonali", employee_gender = "Female",
employee_JoiningDate = "02/09/2017", employee_salary = 50000},
new EmployeeClass() {employee_id = 1003, employee_name = "Vishal", employee_gender = "Male",
employee_JoiningDate = "13/06/2015", employee_salary = 50000},
new EmployeeClass() {employee_id = 1004, employee_name = "Chintu", employee_gender = "Female",
employee_JoiningDate = "16/02/2015", employee_salary = 35000},
new EmployeeClass() {employee_id = 1005, employee_name = "Ankath", employee_gender = "Male",
employee_JoiningDate = "09/11/2017", employee_salary = 35000},
new EmployeeClass() {employee_id = 1006, employee_name = "Saniya", employee_gender = "Female",
employee_JoiningDate = "23/07/2016", employee_salary = 25000},
};
// to find the salary of employess in distinct orders - using Distinct_Method
Console.WriteLine("LINQ-DISTINCT OPERATOR\n");
var res = employeeList.Select(e =>e.employee_salary).Distinct();
Console.WriteLine("Employee Salary using Distinct Method: \n");
foreach (var result in res)
{
Console.WriteLine(result);
}
Console.ReadKey();
}
}
Output:
Example #3
In this program it use LINQ-DistinctIEqualityComparermethod, mostly distinct operator does not compare any complex type, for this approach we move on with this type the IEqualityCompareris used to compare the complex type of collection to retrieve the list uniquely. It has two methods GetHashCode() and Equals() both are used for implementation.
Code:
using System;
using System.Linq;
using System.Collections.Generic;
class LinqDistinct_class
{
internal class Student
{
public intStudentID{ get; set; }
public string StudentName{ get; set; }
}
//USING DISTINCT WITH IEqualityComparer
internal class StudentNameComparer :IEqualityComparer<Student>
{
public bool Equals(Student a, Student b)
{
if (string.Equals(a.StudentName, b.StudentName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
public intGetHashCode(Student obj)
{
return obj.StudentName.GetHashCode();
}
}
public class Program
{
public static void Main(string[] args)
{
List<Student> students = new List<Student>();
students.Add(new Student { StudentID = 1001, StudentName = "Smith" });
students.Add(new Student { StudentID = 1002, StudentName = "Rio" });
students.Add(new Student { StudentID = 1003, StudentName = "Dev" });
students.Add(new Student { StudentID = 1001, StudentName = "Smith" })
students.Add(new Student { StudentID = 1003, StudentName = "Dev" });
students.Add(new Student { StudentID = 1001, StudentName = "Smith" });
students.Add(new Student { StudentID = 1001, StudentName = "Smith" });
students.Add(new Student { StudentID = 1003, StudentName = "Dev" });
students.Add(new Student { StudentID = 1002, StudentName = "Rio" });
students.Add(new Student { StudentID = 1004, StudentName = "Jack" });
varuniqueStudents = students.Distinct(new StudentNameComparer());
Console.WriteLine("USING DISTINCT WITH IEqualityComparer");
Console.WriteLine("-------------------------------------\n");
Console.WriteLine("List of Unique Student Names:\n");
foreach (varget_student in uniqueStudents)
{
Console.WriteLine(get_student.StudentName);
}
Console.ReadLine();
}
}
}
Output:
Conclusion
In this article, we learned about the LINQ-DISTINCT which is used to retrieve the collection of elements uniquely. By using the distinct method we can get the new collection of elements without duplications. Hope the article helps to understand by seeing the above examples with programmatically.
Top of Form
Bottom of Form
Recommended Articles
This is a guide to LINQ Distinct. Here we also discuss the introduction and how distinct works in linq? along with different examples and its code implementation. You may also have a look at the following articles to learn more –