如何使用双键删除列表中的重复对象

时间:2019-05-17 10:41:20

标签: c#

我有列表对象。但是它具有 2 键-itemIditemTypeId重复记录。如何从列表中删除重复项

我尝试了GroupBy-但一次只能使用一个键

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

实际结果:

to1to3

2 个答案:

答案 0 :(得分:15)

您可以使用以下语法将多个字段分组:

var testListNoDups = testList.GroupBy(x => new {x.itemId, x.itemTypeId})
                                  .Select(x => x.First())
                                  .ToList();

答案 1 :(得分:3)

如果要修改现有 class Derived2: public Derived1 { public: Derived2(int &id) : Base(id), Derived1(id) { } }; ,可以尝试testList

RemoveAll

在这里,我们尝试将下一个密钥添加到 HashSet<Tuple<int, int>> keys = new HashSet<Tuple<int, int>>(); testList.RemoveAll(x => !keys.Add(Tuple.Create(x.itemId, x.itemTypeId))); 中,如果失败(即密钥存在于keys中),我们将从keys中删除该项目