Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate object in List with double key

Tags:

c#

I have list object's. But it has duplicate records for 2 key - itemId and itemTypeId. How do I remove duplicates from the list?

I tried GroupBy - but it can only use one key at a time.

public class TestObject
{
        public string Name;
        public int itemTypeId;
        public int itemId;
        public int id;
}

List <TestObject> testList = new List<TestObject>();

TestObject to1 = new TestObject();
TestObject to2 = new TestObject();
TestObject to3 = new TestObject():

to1.id = 1;
to1.itemId = 252;
to1.itemTypeId = 1;
to1.Name = "to1";

to2.id = 2;
to2.itemId = 252;
to2.itemTypeId = 1;
to2.Name = "to2";

to3.id = 3;
to3.itemId = 252;
to3.itemTypeId = 2;
to3.Name = "to3"

testList.Add(to1);
testList.Add(to2);
testList.Add(to3);

var result = testList.GroupBy(x=>x.itemId).Select(g => 
g.First()).ToList();

Actual Result :

to1 and to3

like image 446
Andrew Stark Avatar asked May 17 '19 10:05

Andrew Stark


People also ask

How do you remove duplicates from a key value pair in Python?

We can use loop or dictionary comprehension to remove duplicates from the dictionary in Python. While removing a duplicate value from the dictionary the keys are also removed in the process. If you don't care about retaining the original order then set(my_list) will remove all duplicates.


2 Answers

You can group with multiple fields using the following syntax, grouping will filter out the duplicate entries:

var testListNoDups = testList.GroupBy(x => new {x.itemId, x.itemTypeId})
                                  .Select(x => x.First())
                                  .ToList();
like image 135
Donal Avatar answered Nov 01 '22 13:11

Donal


if you want to modify existing testList, you can try RemoveAll:

 HashSet<Tuple<int, int>> keys = new HashSet<Tuple<int, int>>();

 testList.RemoveAll(x => !keys.Add(Tuple.Create(x.itemId, x.itemTypeId)));     

Here we try to add next key to keys and in case of failure (i.e. key exists in keys) we remove the item from testList

like image 26
Dmitry Bychenko Avatar answered Nov 01 '22 13:11

Dmitry Bychenko