2015-02-23 44 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