在列表中存储一对int

Mik*_*onn 21 c# integer list

如何在List中存储整数对?我知道我可以像他们一样为他们上课:

class Pair  
{
    int i1,i2;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我这样做,我将无法使用该Contains函数来检查给定对是否在列表中.我怎么能这样做,所以我可以轻松地将整数存储在List中,并检查一对整数是否已经存在?我不能使用表,因为不知道会有多少对.

编辑:
忘记添加:在我的程序对(x,y)和(y,x)被视为等于.

编辑:
(x,y)和(y,x)是等于检查是否Point在列表中,但是x并且y不能交换,因为x并且y表示两点之间的连接(整数是点的id,不,我不能使用任何参考等...).当我检查是否List包含连接时,如果它是(x,y)或(y,x)并不重要,但稍后我将需要该信息.

jas*_*son 43

如果您使用的是.NET 4.0,则可以使用Tuple该类

var tuple = new Tuple<int, int>(17, 42);
var otherTuple = Tuple.Create(17, 42);
Run Code Online (Sandbox Code Playgroud)

var list = new List<Tuple<int, int>>();
Run Code Online (Sandbox Code Playgroud)

请注意,如果您继续使用该路线,Tuple<int, int>则需要创建一个自定义实现,IEqualityComparer<Tuple<TFirst, TSecond>>以反映您(x, y)认为相等的相等规则(y, x).然后,您必须通过该比较器对的实例List<T>.Contains(T, IEqualityComparer<T>)(这里TTuple<int, int>你).

class TupleAsUnorderedPairComparer : IEqualityComparer<Tuple<TFirst, TSecond>> {
    public bool Equals(Tuple<TFirst, TSecond> x, Tuple<TFirst, TSecond> y) {
        if(Object.ReferenceEquals(x, y)) {
            return true;
        }
        if(x == null || y == null) {
            return false;
        }
        return x.Item1 == y.Item1 && x.Item2 == y.Item2 ||
               x.Item1 == y.Item2 && x.Item2 == y.Item1;
    }

    public int GetHashCode(Tuple<TFirst, TSecond> x) {
        if(x == null) {
            return 0;
        }
        return x.Item1.GetHashCode() ^ x.Item2.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

否则,如果您不能或不想使用,Tuple那么您将需要IEqualityComparer<Pair>为您的Pair类实现或覆盖Object.EqualsObject.GetHashCode.

class Pair {
    public int First { get; private set; }
    public int Second { get; private set; }
    public Pair(int first, int second) {
        this.First = first;
        this.Second = second;
    }

    public override bool Equals(object obj) {
        if(Object.ReferenceEquals(this, obj)) {
            return true;
        }
        Pair instance = obj as Pair;
        if(instance == null) {
            return false;
        }
        return this.First == instance.First && this.Second == instance.Second ||
               this.First == instance.Second && this.Second == instance.First;
    }

    public override int GetHashCode() {
        return this.First.GetHashCode() ^ this.Second.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

class PairEqualityComparer : IEqualityComparer<Pair> {
    // details elided 
}
Run Code Online (Sandbox Code Playgroud)

如果你使用

list.Contains(pair);
Run Code Online (Sandbox Code Playgroud)

然后它将使用Equals,GetHashCode但如果你使用

list.Contains(pair, new PairEqualityComparer);
Run Code Online (Sandbox Code Playgroud)

然后它将使用PairEqualityComparer.EqualsPairEqualityComparer.GetHashCode.请注意,这些可能比你的实现是不同的Object.EqualsObject.GetHashCode.

最后,如果测试遏制是你经常做的事情,那么a List不是你最好的选择; 你应该使用为此目的设计的类,如a HashSet.