Find and Deletes Duplicates in List of Tuples in C#

后端 未结 4 1375
终归单人心
终归单人心 2021-02-04 01:18

I need to find and remove the duplicates from a List of tuples. Basically, my structure is made like that:

List> myList = new L         


        
4条回答
  •  粉色の甜心
    2021-02-04 01:44

    If you want a solution that amends the list in place, you can make use of a HashSet (or for older frameworks a Dictionary, object> and ignore the value):

    var existing = new HashSet>();
    
    for (int i = myList.Count - 1; i >= 0; i--)
    {
        if (existing.Contains(myList[i]))
        {
            myList.RemoveAt(i);
        }
        else
        {
            existing.Add(myList[i]);
        }
    }
    

    We count backwards without using an iterator (otherwise you'd get errors amending the list while iterating).

    HashSet also has overloads for overriding equality should you need it.

    Personally I'd go for dasblinkenlight's answer for readability.

提交回复
热议问题