Removing duplicates from the bottom of the general list

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?

+5
source share
3 answers

Most LINQ statements keep order : the Distinct () API says that it will take the first instance of every element it encounters. If you want the latest instance, just do:

var res = list.Reverse().Distinct(new DistinctIdentifierComparer());

, , :

var res = list.GroupBy(i => i.Name).Select(g => g.Last());

MSDN:

IGrouping , , . , .

+9

:

public class IdentifierList : List<Identifier>
{
    public void Add(Identifier item)
    {
        this.RemoveAll(x => x.Name == item.Name);
        base.Add(item);
    }
}

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" };

IdentifierList list = new IdentifierList ();
list.Add(idn1);
list.Add(idn2);
list.Add(idn3);
list.Add(idn4);
list.Add(idn5);
list.Add(idn6);
+1

You can Groupand check if there are Count> 1

var distinctWorked = !(res
.GroupBy(a => a.Name)
.Select(g => new{g.Key, Count = g.Count()})
.Any(a => a.Count > 1));
0
source

All Articles