简体   繁体   中英

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

I have a Tuple of pairs with the same type eg: [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. :-)

您可以编写一个实现IEqualityComparer<Tuple<int, int>>的类,并在调用Distinct()时使用它:

pairs.Distinct(new YourComparerClass());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM