Find and Deletes Duplicates in List of Tuples in C#

与世无争的帅哥 提交于 2019-12-02 22:17:39

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.

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

Marsh

Use distinct() method:

myList.Distinct().ToList();
Adam Houldsworth

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!