How to Remove Duplicates and Get Distinct records from List using LINQ?

01using System;
02
03using System.Collections.Generic;
04
05using System.Data;
06
07using System.Linq;
08
09namespace AbundantCode
10
11{
12
13internal class Program
14
15{
16
17//How to Remove Duplicates and Get Distinct records from List using LINQ ?
18
19private static void Main(string[] args)
20
21{
22
23List<Employee> employees = new List<Employee>()
24
25{
26
27new Employee { EmpID = 1 , Name ="Ram"},
28
29new Employee { EmpID = 2 , Name ="Magi"},
30
31new Employee { EmpID = 3 , Name ="Muni"},
32
33new Employee { EmpID = 3 , Name ="Natarajan"}
34
35};
36
37//Gets the Distinct List
38
39var DistinctItems = employees.GroupBy(x => x.EmpID).Select(y => y.First());
40
41foreach(var item in DistinctItems)
42
43Console.WriteLine(item.Name);
44
45Console.ReadLine();
46
47}
48
49}
50
51public class Employee
52
53{
54
55public string Name { getset; }
56
57public int EmpID { getset; }
58
59}
60
61}

Post a Comment

0 Comments

Close Menu