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
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.
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();
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
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