How can I test if value of int is for example 1,2,4 or 5? I thought i could do something like this but apparently not.
if(someInt == (1||2||4||5))
Use LINQ:
if ((new[] {1,2,4,5}).Contains(someInt))
Write an extension method
static class MiscExtensions
{
static bool EqualToAny<T>(this T i, params T[] items)
{
return items.Any(x => x.Equals(i));
}
}
And use it like so
static class Program
{
static void Main(string[] args)
{
int myNumber = 5;
if (myNumber.EqualToAny(1, 2, 3, 4, 5))
Console.WriteLine("Hello, World");
}
}
As an alternative you can use:
switch(someInt)
{
case 1:
case 2:
case 4:
case 5:
DoYourStuff();
break;
}
There are two ways I can think of.
Or all the comparisons.
if (someInt == 1 || someInt == 2 || someInt == 4 || someInt == 5) {
}
Or for a more flexible solution see if someInt is in an array.
if (Array.BinarySearch(new[] { 1, 2, 4, 5 }, someInt ) != -1) {
}
You need to write your if statement like this
if (someInt==1 || someInt==2 || someInt==4 || someInt==4)
Or you could use a switch statement
switch (someInt)
{
case 1:
case 2:
case 4:
case 5:
// do something
break;
}
Breaking down your attempted code is quite interesting. You wrote:
if(someInt == (1||2||4||5))
I guess in your head you read it as, if someInt equals 1 or 2 or 4 or 5. And if computers behaved like humans then this would work. But we all know that computers don't behave like that!
The == equality operator, a binary operator, returns true when its two operands are equal. So that means, in your version, if it compiled, you would need someInt to be equal to (1||2||4||5). And for that to even be meaningful, we would need (1||2||4||5) to evaluate to a single value, instead of producing a compile error. And, if it did evaluate to a single value, then it could not have the meaning which you want. Because you want the test to return true when someInt is equal to one of four candidate values.
The bottom line is that == tests for exact equality between precisely two values.
You can't do it like that. Instead use:
if(someInt == 1 || someInt == 2 || someInt == 4 || someInt == 5)
Or also you could use something like this:
if((new List<int>() {1,2,4,5}).Contains(someInt) == true)
Related
I am wondering if there is a way to check multiple while loop conditions using the same variable. That's a bit vague, but this example should clear it up:
while (myFunction(x) == 0 || myFunction(x) == 13639 || myFunction(x) == -4261.9583)
{ x++; }
Is it possible to only evaluate myFunction(x) once per loop while checking the three conditions, so that the function doesn't have to run three separate times for a result that is the same each time?
I am doing this for optimization/efficiency purposes. myFunction() could be a pretty time-consuming function, so I want it to run the minimum amount of times necessary.
Typically I would define the value of myFunction(x) before I start the while loop, but in this case, the value of myFunction(x) will be changing as the loop goes through each iteration, since the value of x will be changing.
Yes, this can be done:
double result;
while ((result = myFunction(x)) == 0 || result == 13639 || result == -4261.9583)
{ x++; }
Three options:
Do it backwards
Check a list for the result rather than checking the result against the list.
var list = new float[] { 0F, 13639F, -4261.9583F );
while (list.Contains(myFunction(x))
{
x++;
}
Write a function
Extracting the logic to another function is always a nice way to break down the problem.
bool IsValid(float input)
{
var result = myFunction(input);
return (result == 0 || result == 13639 || result == -4261.9583);
}
while (IsValid(x))
{
x++;
}
Use while(true)
Whenver the condition of a while loop is complicated, a common option is to remove the check from the () and put it in the {} instead. When you do this, use while (true).
while (true)
{
var result = myFunction(x);
if (result != 0 && result != 13639 && result != -4261.9583) break;
x++;
}
You can do this simply by moving the check into a separate method, which takes the return value of the function as parameter, and then performs the 3 checks on the value directly and returns a boolean accordingly.
Assuming the function returns a int typed value this may for example look something like this:
bool CheckResultValue(int value) {
return value == 0 || value == 13639 || value == -4261.9583;
}
Then your while loop could look something like this:
while (CheckResultValue(myFunction(x)))
{ x++; }
I have the following integer that I would like to check the value with an if statement.
int myInt = 3;
I tried this code which works, but I don't like having to write the variable name over and over.
if (myInt == 0 || myInt == 2 || myInt == 3 || myInt == 4)
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
To demonstrate what I would like to ideally have, I tried something like this:
if (myInt == (0 | 2 | 3 | 4))
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
But this doesn't work because the | is not quite the right operator because there is a type mismatch.
I then tried this, which also worked fine, but I still don't like having to declare an extra array.
if ((new int[] { 0, 2, 3, 4 }).Contains(myInt))
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
The question is:
Is there an operator that can satisfy what I'm trying to accomplish without declaring an additional array or asking for the same variable name over and over with the || operator?
Your question is
Is there an operator that can satisfy what I'm trying to accomplish without declaring an additional array
but it really should be
Is there an operator that can satisfy what I'm trying to accomplish without declaring an additional array every time
There is nothing wrong with having that array once (and initializing it once), but there is a lot wrong with allocating it (and by extension GCing it later) every single time. So You need to declare an array once, something like
private static int matchArray[] = new int[] { 0, 2, 3, 4 };
and later just
if (matchArray.Contains(myInt)) ...
EDIT
If your match array is small, by any means use the answer by #JohnField and not this one - I stand corrected!
There is possibly a way to achieve what you want to do. They are called enum flags. Here there is a nice answer that explains how they work.
They way you want to use integers remind me of an enum where you have possibly multiple choices. Let's take the following case for instance:
[Flags]
enum DaysOfTheWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
you can declare a variable as follow:
DaysOfTheWeek daysOfTheWeek;
daysOfTheWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Wednesday | DaysOfTheWeek.Friday;
and then check if your enum contains one of the values assigned above:
if((daysOfTheWeek & DaysOfTheWeek.Monday) == DaysOfTheWeek.Monday)
{
// Contains Monday!
}
else
{
// DOES NOT Contain Monday!
}
or from .NET 4 onwards:
if(daysOfTheWeek.HasFlag(DaysOfTheWeek.Monday))
{
...
}
Clearly this method is more elegant as long as you need to check for a small number of cases. If you have big array to check against, it would not be a suitable approach.
See, I'm just thinking... why not use a switch?
https://msdn.microsoft.com/en-us/library/06tc147t.aspx
int myInt = 3;
switch (myInt)
{
case 0:
case 2:
case 3:
case 4:
// Match
break;
default:
// No match
break;
}
If your array is in order, Array.BinarySearch will be more efficient than Contains, especially if the array has more than a few elements.
if (Array.BinarySearch(checkArray, myInt) >= 0)
;//match
else
;//no match
Usually, however, the best choice for the Contains operation is the HashSet. Thanks to JohanLarsson for pointing that out.
You could use a switch-case, but it could be argued that this looks messy.
switch (myInt)
{
case 0: //Add a comment to make it clear that
case 2: //this is a deliberate fall-through and
case 3: //not a mistake. (E.g. "//Deliberate
case 4: //fall-through for 0, 2, 3, 4")
//Insert code here in this section to do something
Debug.WriteLine("Match");
break; //Break statement is required to indicate end of section
default:
//The default section runs like an "else" statement
//It is optional and will run if none of the above
//cases are applicable.
Debug.WriteLine("No Match");
break;
} //end switch-case
How can I use && operator in switch case?
This is what i want to do:
private int retValue()
{
string x, y;
switch (x && y)
{
case "abc" && "1":
return 10;
break;
case "xyz" && "2":
return 20;
break;
}
}
My problem is that "abc" and "1" are both of type string and the compiler gives me message that:
"operator && cannot be applied to string"
There is no such operator in switch statements. The switch statement operates on a single variable which is a value type or a string. See:
http://www.dotnetperls.com/switch
http://msdn.microsoft.com/en-us/library/06tc147t.aspx
The real problem in your example is that both in the switch expression, and in case labels, you are applying && to strings. You cannot apply && to strings, it only works on booleans (unless you overload it and define a new function that does work on strings).
What you are trying to accomplish is probably to simultaneously check the values of two different variables with one switch. This is impossible; switch only checks one variable at a time. The solution is to use if statements or a specialized CheckStrings(string s1, string s2) method (which may or may not use if statements).
In a comment you have expressed concerns with length. Observe:
private int retValue(string x, string y)
{
if (x == "abc" && y == "1") return 10;
if (x == "xyz" && y == "2") return 20;
throw new Exception("No return value defined for these two strings.")
}
Shorter, even if you discount the gains from skipping redundant break; statements and putting returns on the same line.
Despite there is an accepted answer already...
To achieve logical AND in switch, it has to be done like this:
switch(x + y)
{
case "abc1":
return 10;
break;
case "xyz2":
return 20;
break;
}
Which works.
For logical OR see zey answer.
You mean like that ?
switch (value)
{
case "abc":
case "1":
return 10;
case "xyz":
case "2":
return 20;
}
If you are using C# 8 and above below code snippet will yield the desired result. This is using pattern matching with expression future.
string x = "abc", y = "2";
var result = (x, y) switch
{
("abc","1") => 10,
("xyz","2") => 20,
(_,_) => 0
};
Console.WriteLine($"Arguments : {x}, {y}, result : {result}");
switch statement can only be applied to integer values or constant expressions. If you want to check your conditions on string type variable, then you should use if-else-if structure.
I know I can do it like this:
if(myint == 1 || myint == 2 || myint ==3) //etc...
But I feel like there must be a more efficient way to code this. Is there a way to possibly make a statement like this work?
if(myint.Contains(1 || 2 || 3 || 4))
you can do inverse
new List<int>{1,2,3,4}.Contains(myInt)
Note that there is also Enumerable.Any, but Contains would work for .net 2.0 too.
Close, try the following.
It will take a collection and return true if your int is in the collection:
if (new[] { 1, 2, 3, 4 }.Contains(myint))
//Do something
new[] { 1, 2, 3, 4 } represents an array of integers.
The Contains method is an extension of IEnumerable<T> and will be available to anything that implements it.
In a lot of situations we have to do something like this:
if (someVariable == value1 || someVariable == value2 || someVariable == value1...)
Would it be nice if we can do this in following manner:
if (someVariable in {value1, value2, value3...}
We can do this
int[] arr = {value1, value2, value3....};
if (arr.Contains(someVariable)) ...
But its still overwhelming, to my opinion. Why there isn't a support for this syntax, or there is but I don't know about it?
I think this may be about as concise as you may get:
if (new int[] { 1, 2, 3 }.Contains(2))
{
Console.WriteLine("bleh");
}
Use a HashSet for this:
var hs = new HashSet<int>();
hs.Add(1);
hs.Add(2);
...
if(hs.Contains(x))
{
//bingo!
}
How about
switch (someVariable)
{
case value1:
case value2:
case value3:
case value12345:
doSomething();
break;
default:
doSomethingElse();
break;
}
Use the Contains method of HashSet. I am not sure how this improves code clarity since you are still forced to check all three conditions.