Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all distinct combinations of pairs in C# / LINQ?

Tags:

c#

linq

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();
    }
}
like image 877
mamuesstack Avatar asked May 21 '14 13:05

mamuesstack


2 Answers

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. :-)

like image 50
Heinzi Avatar answered Nov 17 '22 21:11

Heinzi


You could write a class that implements IEqualityComparer<Tuple<int, int>> and use that in a call to Distinct():

pairs.Distinct(new YourComparerClass());
like image 5
Dennis_E Avatar answered Nov 17 '22 21:11

Dennis_E