I am unable to remove the duplicates from collection , i have implemented IEqualityComparer for the class Employee still i am not getting the output
static void Main(string[] args) { List<Employe> Employeecollection = new List<Employe>(); Employeecollection.Add(new Employe("abc","def")); Employeecollection.Add(new Employe("lmn","def")); Employeecollection.Add(new Employe("abc", "def")); IEnumerable<Employe> coll = Employeecollection.Distinct(new Employe()); foreach (Employe item in coll) { Console.WriteLine(item.fName + " " + item.lName ); } }
The Below is the Employee class implementation , here i implemented IEqualityComparer
class Employe : IEqualityComparer<Employe> { public string fName { get; set; } public string lName { get; set; } public Employe() { } public Employe(string firstName, string LastName) { this.fName = firstName; this.lName = LastName; } #region IEqualityComparer<pcf> Members public bool Equals(Employe x, Employe y) { if (x.fName == y.fName && x.lName == y.lName) { return true; } return false; } public int GetHashCode(Employe obj) { return obj.GetHashCode(); } #endregion }
We can remove all duplicates like this by using GroupBy and Select methods provided by LINQ . First, we group our list so that we will create groups for each name in the List. Then we use Select to only select the first objects in each group. This will result in the removal of the duplicates.
c# - Linq distinct doesn't call Equals method - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
Linq, acts upon 2 collections. It returns a new collection that contains the elements that are found. Union removes duplicates. So this method can be thought of as two actions: it combines the two collections and then uses Distinct() on them, removing duplicate elements.
C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).
Forget IEqualityComparer and just use Linq directly:
EmployeeCollection.GroupBy(x => new{x.fName, x.lName}).Select(g => g.First());
Here is a good tutorial
public int GetHashCode(Employe obj) { return obj.fname.GetHashCode() ^ obj.lname.GetHashCode(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With