I need to find and remove the duplicates from a List of tuples. Basically, my structure is made like that:
List<Tuple<string, string>> myList = new List<Tuple<string, string>>();
****
private void FillStructure()
{
myList.Add(Tuple.Create<string, string>("A", "B"));
myList.Add(Tuple.Create<string, string>("A", "C"));
myList.Add(Tuple.Create<string, string>("C", "B"));
myList.Add(Tuple.Create<string, string>("C", "B")); // Duplicate
myList.Add(Tuple.Create<string, string>("A", "D"));
FindAndRemoveDuplicates(myList);
}
private void FindAndRemoveDuplicates(List<Tuple<string, string>> myList)
{
// how can I perform this ?
}
I can't use a Dictionary because I can have the same key but different values! Thank you in advance
To remove duplicate tuples from a list of tuples: Use the set() class to convert the list to a set of tuples. Any duplicate tuples will automatically get removed after the conversion. Use the list() class to convert the set back to a list.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Tuples A Tuple represents a collection of objects that are ordered and immutable (cannot be modified). Tuples allow duplicate members and are indexed.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With