Find and Deletes Duplicates in List of Tuples in C#

后端 未结 4 1376
终归单人心
终归单人心 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条回答
  •  梦毁少年i
    2021-02-04 01:55

    You can use HashSet for this purposes (http://msdn.microsoft.com/en-us/library/bb359438.aspx)

    class SameTuplesComparer : EqualityComparer> 
    {
       public override bool Equals(Tuple t1, Tuple t2)
       {
          return t1.Item1.Equals(t2.Item1) && t1.Item2.Equals(t2.Item2)
       }
    
    
       public override int GetHashCode(Tuple t)
       {
         return base.GetHashCode();
       }
    }
    

    So if you write your own comparer, you can compare strings a little differently (as example, not casesensetive):

    class SameStringTuplesComparer: EqualityComparer> 
    {
       public override bool Equals(Tuple t1, Tuple t2)
       {
          return t1.Item1.Equals(t2.Item1, StringComparison.CurrentCultureIgnoreCase) && t1.Item2.Equals(t2.Item2, StringComparison.CurrentCultureIgnoreCase)
       }
    
    
       public override int GetHashCode(Tuple t)
       {
         return base.GetHashCode();
       }
    }
    

    Then in code:

    var hashSet = new HashSet>(list, new SameTuplesComparer());
    

    Or without your own comparer:

    var hashSet = HashSet>(list);
    

    Now you can add elements to hashSet and all elements will be unique. After you done with adding elements you can convert it to list again:

    var uniquedList = hashSet.ToList();
    

    Or just use list.Distinct().ToList()

提交回复
热议问题