c# - 如何在 C#/LINQ 中获取所有不同的对组合?

标签 c# linq

我有一个相同类型的元组,例如:[1,1][1,2][2,1][2,1]

我需要计算不同的组合:[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();
}

您将如何实现通用的 GetDistinctPairs(pairs) ?

解决方法:

正如 Heinzi 和 Dennis_E 所建议的,我实现了一个通用的 IEqualityComparer。欢迎改进:-)

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

最佳答案

有一个 Enumerable.Distinct overload它允许您指定 IEqualityComparer .

提供自定义 IEqualityComparer<Tuple<T, T>>认为 [1, 2] 和 [2, 1] 相等。

实现应该是微不足道的,留给读者作为练习。 :-)

关于c# - 如何在 C#/LINQ 中获取所有不同的对组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23783981/

相关文章:

c# - .NET:EventHandler 竞争条件修复如何工作?

c# - 在列表中添加对象的两个变量

c# - 使用 Linq to Entities 的装箱值

c# - AspNetUsers 的主键不一致 "Object reference not set to an instance of an object"

c# - 在 stimulsoft 报告中处理关系时出现错误

c# - 使用正则表达式从 SQL 查询中提取表和列

c# - "Object Reference Not Set..."对象创建

c# - 如何使用 BinaryReader 并将数据正确输入文件?

.net - 为什么 Linq 函数可用于可以是字符串类型的变量

c# - LINQ - 重构。包含对 IEnumerable<string> 的比较以区分大小写