I have a Tuple of pairs with the same type e.g.: [1,1][1,2][2,1][2,1]
I need to calculate the distinct combinations: [1,1][1,2]
public void DistinctPairsTest()
{
IList<Tuple<int, int>> pairs = new List<Tuple<int, int>>();
pairs.Add(Tuple.Create(1, 1));
pairs.Add(Tuple.Create(1, 2));
pairs.Add(Tuple.Create(2, 1));
pairs.Add(Tuple.Create(2, 1));
IList<Tuple<int, int>> distinctPairs = GetDistinctPairs(pairs);
Assert.AreEqual(2, distinctPairs.Count);
}
private IList<Tuple<T, T>> GetDistinctPairs<T>(IList<Tuple<T, T>> pairs)
{
throw new NotImplementedException();
}
How would you implement the generic GetDistinctPairs(pairs) ?
Solution:
as Heinzi and Dennis_E suggested, I implemented a generic IEqualityComparer. Improvements are welcome :-)
public class CombinationEqualityComparer<T> : IEqualityComparer<Tuple<T, T>>
{
public bool Equals(Tuple<T, T> x, Tuple<T, T> y)
{
bool equals = new HashSet<T>(new[] { x.Item1, x.Item2 }).SetEquals(new[] { y.Item1, y.Item2 });
return equals;
}
public int GetHashCode(Tuple<T, T> obj)
{
return obj.Item1.GetHashCode() + obj.Item2.GetHashCode();
}
}
There is an Enumerable.Distinct
overload which allows you to specify an IEqualityComparer
.
Provide a custom IEqualityComparer<Tuple<T, T>>
that considers [1, 2] and [2, 1] to be equal.
The implementation should be trivial and is left as an exercise to the reader. :-)
You could write a class that implements IEqualityComparer<Tuple<int, int>>
and use that in a call to Distinct():
pairs.Distinct(new YourComparerClass());
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