We often need to select distinct records from a list or from database. In Linq, we can select distinct records from a list or collection using Distinct method.
Suppose we have a list with the name Employees and we want to select only Distinct records from this list then this can be done by using Distinct method.
Here is the code for this
static void Main(string[] args)
{
List<string> employees = new List<string> { "Abhishek", "Shubham", "Sameer", "Shubham" };
var distinctEmployees = employees.Distinct().ToList();
foreach (var emp in distinctEmployees)
{
Console.WriteLine(emp);
}
Console.Read();
}
In the above code, we are creating a list employees with employee names in which name Shubham is added twice. Now we want to get distict records out of the employees list.
For this, we have used following statement
var distinctEmployees = employees.Distinct().ToList();
This statement will assign distinct records to distictEmployees variable. In the next step, we are iterating the distictEmployees variable and writing the values to console.
The output will look like this
Abhishek
Shubham
Sameer
0 Comment(s)