Below is a sample source code demonstrating on how to remove duplicates and get distinct records in List using LINQ and C#?
How to Remove Duplicates and Get Distinct records from List using LINQ?
using System; using System.Collections.Generic; using System.Linq; namespace AbundantCode { public class Employee { public int EmpID { get; set; } public string Name { get; set; } } internal class Program { //How to Remove Duplicates and Get Distinct records from List using LINQ ? private static void Main(string[] args) { List<Employee> employees = new List<Employee>() { new Employee { EmpID = 1 , Name ="AC"}, new Employee { EmpID = 2 , Name ="Peter"}, new Employee { EmpID = 3 , Name ="Michael"}, new Employee { EmpID = 3 , Name ="Michael"} }; //Gets the Distinct List var DistinctItems = employees.GroupBy(x => x.EmpID).Select(y => y.First()); foreach (var item in DistinctItems) Console.WriteLine(item.Name); Console.ReadLine(); } } }
What if you want to find uniqueness over both name and id? As an examaple
List employees = new List()
{
new Employee { EmpID = 1 , Name =”AC”},
new Employee { EmpID = 2 , Name =”Peter”},
new Employee { EmpID = 3 , Name =”Michael”},
new Employee { EmpID = 3 , Name =”Michael”}
new Employee { EmpID = 3 , Name =”Michael”}
new Employee { EmpID = 4 , Name =”Michael”}
};
results would be:
ID, Name
1, AC
2, Peter
3, Michael
4, Michael
The existing code takes care of it … am assuming that
1, AC
2, Peter
3, Michael
4, Michael
In the result , 3 – Michael and 4- Michael is definitely unique . Are you referring to the uniqueness of name Or id ?
I would like to determine the uniqueness of by both name AND id. In your code example
var DistinctItems = employees.GroupBy(x => x.EmpID).Select(y => y.First());
the uniqueness is for EmpID only. How to modify this to include the Name?
var DistinctItems = employees.GroupBy(x => new { x.EmpID, x.Name }).Select(y => y.First());
Thanks a lot. It worked fine for me 🙂
Thanks its working 🙂
Why do you need the “.Select(y => y.First())? at the end of line 39?
help for all column distinct from database
List duplicates = lst.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList();
Lee