I am trying to remove a duplicate element from the bottom of a general list. I have a class defined below
public class Identifier
{
public string Name { get; set; }
}
And I defined another class that implements IEqualityComparer to remove duplicates from a list
public class DistinctIdentifierComparer : IEqualityComparer<Identifier>
{
public bool Equals(Identifier x, Identifier y)
{
return x.Name == y.Name;
}
public int GetHashCode(Identifier obj)
{
return obj.Name.GetHashCode();
}
}
However, I am trying to remove old items and keep the last. For example, if I have a list of identifiers defined below
Identifier idn1 = new Identifier { Name = "X" };
Identifier idn2 = new Identifier { Name = "Y" };
Identifier idn3 = new Identifier { Name = "Z" };
Identifier idn4 = new Identifier { Name = "X" };
Identifier idn5 = new Identifier { Name = "P" };
Identifier idn6 = new Identifier { Name = "X" };
List<Identifier> list = new List<Identifier>();
list.Add(idn1);
list.Add(idn2);
list.Add(idn3);
list.Add(idn4);
list.Add(idn5);
list.Add(idn6);
And I implemented
var res = list.Distinct(new DistinctIdentifierComparer());
How can I make sure, using various, that I keep idn6 and delete idn1 and idn4?
source
share