Jtg
Jtg

Reputation: 11

Remove duplicate from List of objects c#

I have a category in my object how can I remove duplicates from each category if there is a duplicate existence based on each category in the list concept.

Please see my requirement below.

Category    Name
-------    ------- 
A           1
A           1 
A           2 
B           1 
B           1
B           3

Final Result should be like

Category    Name
-------    ------- 
A           1
A           2 
B           1 
B           3

Upvotes: 0

Views: 81

Answers (1)

niklas32
niklas32

Reputation: 11

Caius Jard's second comment is the reply you really want. You want to use the Distinct method : var myNonDuplicateList = initalList.Distinct();

But in order to be able to use that method correctly, since this is a class (which has more fields compared to List) you need to implement the Equals method.

 public override bool Equals(object x, object y)
    {
        return  (x.Category == y.Category) && (x.Name == y.Name);
    }

Upvotes: 1

Related Questions