EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

LINQ Distinct

Home » Software Development » Software Development Tutorials » Software Development Basics » LINQ Distinct

LINQ Distinct

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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};

Popular Course in this category
Sale
Software Testing Training (9 Courses, 2 Projects)9 Online Courses | 2 Hands-on Projects | 60+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (7,897 ratings)
Course Price

View Course

Related Courses
Selenium Automation Testing Training (9 Courses, 4+ Projects, 4 Quizzes)Appium Training (2 Courses)JMeter Testing Training (3 Courses)

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:

LINQ Distinctis -1.1

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:

LINQ Distinctis -1.2

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:

LINQ Distinctis -1.3

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:

LINQ Distinctis -1.4

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 –

  1. LINQ Inner Join
  2. Oracle XMLTABLE
  3. ASP.NET UpdatePanel
  4. Asset Backed Securities

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Dot NET
  • LINQ
    • LINQ Include
    • LINQ Aggregate
    • LINQ Distinct
    • LINQ Inner Join
    • LINQ Left Join
    • LINQ Except
    • LINQ SelectMany
    • LINQ Union
    • LINQ Sum
    • LINQ any
    • LINQ Where
    • LINQ Contains
    • LINQ Intersect
    • LINQ Join
    • LINQ Select
    • LINQ Sort
  • .Net
    • What is .Net?
    • What is .NET Core
    • .NET Framework Architecture
    • Career in ASP.NET
    • ASP.NET Core JWT Authentication
    • Uses of .Net
    • .NET Interview Questions
    • How to Install .NET
    • MVC Architecture
    • Entity Framework in MVC
    • ViewModel in MVC
    • MVC DropDownList
    • MVC ViewData
    • Partial View in MVC
    • TempData in MVC
    • Aggregation in OOPS
    • LINQ OrderBy Desc
    • LINQ orderby
  • VB.NET
    • What is VB.Net
    • VB.Net Data Types
    • VB.NET Operators
    • VB.Net Loops
    • VB.Net for Loop
    • VB.NET Controls
    • Inheritance in VB.Net
    • Exception Handling in VB.NET
    • VB.Net Events
    • VB.Net String Functions
    • VB.NET Interview Questions
  • ADO.NET
    • What is ADO.NET
    • ADO.NET Interview Questions

Related Courses

.NET Course Training

VB.NET Training Course

ADO.NET Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Special Offer - Software Testing Training Learn More