Find and Deletes Duplicates in List of Tuples in C#

后端 未结 4 1370
终归单人心
终归单人心 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:36

    You can use Distinct() method of LINQ, like this:

    myList = myList.Distinct().ToList();
    

    Note that this would re-create the list, rather than removing the duplicates in place.

    0 讨论(0)
  • 2021-02-04 01:44

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

    var existing = new HashSet<Tuple<string, string>>();
    
    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<T> also has overloads for overriding equality should you need it.

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

    0 讨论(0)
  • 2021-02-04 01:45

    Use distinct() method:

    myList.Distinct().ToList();
    
    0 讨论(0)
  • 2021-02-04 01:55

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

    class SameTuplesComparer<T1, T2> : EqualityComparer<Tuple<T1, T2>> 
    {
       public override bool Equals(Tuple<T1, T2> t1, Tuple<T1, T2> t2)
       {
          return t1.Item1.Equals(t2.Item1) && t1.Item2.Equals(t2.Item2)
       }
    
    
       public override int GetHashCode(Tuple<T1, T2> 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<Tuple<string, string>> 
    {
       public override bool Equals(Tuple<string, string> t1, Tuple<string, string> t2)
       {
          return t1.Item1.Equals(t2.Item1, StringComparison.CurrentCultureIgnoreCase) && t1.Item2.Equals(t2.Item2, StringComparison.CurrentCultureIgnoreCase)
       }
    
    
       public override int GetHashCode(Tuple<string, string> t)
       {
         return base.GetHashCode();
       }
    }
    

    Then in code:

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

    Or without your own comparer:

    var hashSet = HashSet<Tuple<string, string>>(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()

    0 讨论(0)
提交回复
热议问题