Remove objects with a duplicate property from List

后端 未结 4 554
陌清茗
陌清茗 2021-02-04 23:03

I have a List of objects in C#. All of the objects contain a property ID. There are several objects that have the same ID property.

How can I trim the List (or make a

4条回答
  •  隐瞒了意图╮
    2021-02-04 23:33

    Not sure if anyone is still looking for any additional ways to do this. But I've used this code to remove duplicates from a list of User objects based on matching ID numbers.

    private ArrayList RemoveSearchDuplicates(ArrayList SearchResults)
    {
        ArrayList TempList = new ArrayList();
    
        foreach (User u1 in SearchResults)
        {
            bool duplicatefound = false;
            foreach (User u2 in TempList)
                if (u1.ID == u2.ID)
                    duplicatefound = true;
    
            if (!duplicatefound)
                TempList.Add(u1);
        }
        return TempList;
    }
    

    Call: SearchResults = RemoveSearchDuplicates(SearchResults);

提交回复
热议问题