我有一对值 int x 和 int y,想看看这对值是否出现在值对的二维数组中。
通常,我现在拥有的是:
if ((x == 5 && y == 2) || (x == 6 && y == 1) || ETC)
return true;
由于有相当多的可能性需要返回 true,我认为使用这些值对创建一个数组并查看 x 和 y 是否在该数组中作为一对一起出现会更容易:
int[,] arrayOfPairs = new int[,]
{
{5, 2},
{6, 1},
};
我知道在 C++ 中我们可以使用 std::find 来做到这一点,但不知道在 C# 中是否可行。
感谢您的帮助!
最佳答案
尝试使用 Tuple<int, int>
的数组...例如:
Tuple<int, int>[] pairs = new Tuple<int, int>[]
{
Tuple.Create(5, 2),
Tuple.Create(6, 1),
};
然后你可以像这样确定一个元素是否存在:
if (Array.IndexOf(pairs, Tuple.Create(3, 4)) != -1)
{
// element exists.
}
还有更巧妙的方法可以使用 LINQ 来完成此操作:
if (pairs.Any(x => x == Tuple.Create(3, 4)))
{
// element exists
}
根据 @Martheen 的建议,以下是如何使用 HashSet
来实现.
HashSet<Tuple<int, int>> pairs = new HashSet<Tuple<int, int>>()
{
Tuple.Create(5, 2),
Tuple.Create(6, 1),
};
可以按如下方式使用:
if (pairs.Contains(Tuple.Create(3, 4)))
{
// element exists
}
由于您使用的是 Unity,因此您可以替换 Tuple
对于Vector2
。那么我的第一个方法就可以工作了。
此外,如果您想获得使用 HashSet
的速度优势但无权访问该集合,那么您可以使用常规的旧 Hashtable
.
// initialize pairs
Hashtable pairs = new Hashtable().
pairs.Add(new Vector2(5F, 2F), true);
pairs.Add(new Vector2(6F, 1F), true);
// check for existence
if (pairs.ContainsKey(new Vector2(3F, 4F))
{
// element exists
}
关于c# - 将一对值与值对数组进行比较 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41900045/