- Home /
Test All Variables in an Array C#
So lets say I have an array:
int[] num;
And then I assigned 3 variables in the array.
num[0] = 1;
num[1] = 2;
num[2] = 3;
But now, I want to do:
if (num[0] == 5 && num[1] == 5 && num[2] == 5) {
//Do stuff
}
Is there anyway to test all the variables at once? Like:
if (num[All Numbers] == 5){
}
I hope this makes sense, and thank you!
Answer by fafase · Jul 08, 2014 at 02:04 AM
bool AllSame(int value){
for(int i = 0; i < num.Length;i++)
{
if(num[i] != value)return false;
}
return true;
}
you can also use extension:
public static Utility{
public static bool AllSame(this int[] num, int value){
for(int i = 0; i < num.Length;i++)
{
if(num[i] != value)return false;
}
return true;
}
}
Ok, so just to clarify, this would create a bool called AllSame and later I could do:
if (AllSame == true) {
//Stuff
}
Correct?
I would recommend to use the extension then you go.
int[]num = new int[size];
// add values
if( num.AllSame(5) )
{
// They are all the same
}
if you happen to know they are ordered then you only to check first and last.
public static Utility{
public static bool AllSameOrderedSerie(this int[] num, int value){
if(num[0] != value)return false;
if(num[nul.Length - 1] != value)return false;
return true;
}
}
Your answer
Follow this Question
Related Questions
How can I use the same script on multiple objects without conflicting variables. 2 Answers
How to make an array with different variables and visible in Unity's inspector 1 Answer
how to get a variable like Layermask but for tags 2 Answers
How to assign variables to each GameObject in an array 1 Answer