2015-02-23 51 views
1

我想检查数组列表包含顺序颠倒因素数组,如果没有,添加它们:列表总是不包含数组甚至是

var faclist = new List<int[]>(); 
var factors = new int[2] {i, j}; 
if (!faclist.Contains(factors.Reverse())) 
{ 
    faclist.Add(factors); 
} 

但是这个代码总是不正确的,甚至有是具有相反因素的阵列。

回答

5

.Contains适用于.Equals方法。默认情况下,如果两个实例(引用)相同,则.Equals方法仅返回true

解决此问题的一种可能方法 - 如果因素数目固定 - 正在使用Tuple<int,int>。您可以定义一个`元组类的Reverse法:

public static class Foo { 

    public static Tuple<T2,T1> Reverse<T1,T2> (this Tuple<T1,T2> tuple) { 
     return new Tuple<T2,T1>(tuple.Item2,tuple.Item1); 
    } 

} 

然后用简单的调用它:

Tuple<int,int> t = new Tuple<int,int>(3,5); 
Tuple<int,int> t2 = t.Reverse(); 

如果没有,你可以定义一个包装类,执行平等检查描述here

或者另一种替代方案是在方法中自己提供一个相等检查器,如@xanatos answer所述。

演示:

$ csharp 
Mono C# Shell, type "help;" for help 

Enter statements below. 
csharp> var t1 = new Tuple<int,int>(3,2); 
csharp> var t2 = new Tuple<int,int>(3,2); 
csharp> t1.Equals(t2); 
true 
csharp> int[] t1 = new int[] {3,2}; 
csharp> int[] t2 = new int[] {3,2}; 
csharp> t1.Equals(t2); 
false 
3

至于写CommuSoft,因为数组没有实现在你的思考方式比较(他们这样做只是参考比较)

另一种解决方案是实现一个平等比较器:

public class IntArrayComparison : IEqualityComparer<int[]> { 
    public bool Equals(int[] x, int[] y) { 
     if (x == null) { 
      return y == null; 
     } 

     if (y == null) { 
      return false; 
     } 

     return x.SequenceEqual(y); 
    } 

    public int GetHashCode(int[] obj) { 
     throw new NotImplementedException(); 
    } 
} 

if (!faclist.Contains(factors.Reverse().ToArray(), new IntArrayComparison())) { 

,然后用它在Contains方法。 (请注意,我必须要改变的Reverse()结果返回到一个数组,因为Reverse()返回IEnumerable<T>

+0

太糟糕了,你不能只是一个插件功能''像[这一个](https://开头MSDN。 microsoft.com/en-us/library/vstudio/bb348567%28v=vs.100%29.aspx)。 – 2015-02-23 13:08:23

+0

@CommuSoft看看http://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer – xanatos 2015-02-23 13:10:54

+0

是的,但我想知道他们为什么不提供直接注入函数的方法。除了'.Equals'(well'.GetHashCode'),没有太多额外的功能是有用的...... – 2015-02-23 13:14:06