Reputation: 9915
Is it possible to use switch statement over if else when condition is made of 2 variables.
Thanks.
added:
foreach( DataRow row in workingTable.Rows )
{
if( isKey && isValue )
workingDictionary.Add( row[ keyIdentifier ].ToString(), row[ valueIdentifier ] );
else if( isKey && !isValue )
workingDictionary.Add( row[ keyIdentifier ].ToString(), row[ sValueIdentifier ] );
else if( !isKey && isValue )
workingDictionary.Add( row[ sKeyIdentifier ].ToString(), row[ valueIdentifier ] );
else
workingDictionary.Add( row[ sKeyIdentifier ].ToString(), row[ sValueIdentifier ] );
}
Upvotes: 0
Views: 1037
Reputation: 633
Or you could rewrite the code something like this...
foreach( DataRow row in workingTable.Rows )
{
int keyIndex = isKey ? keyIdentifier : sKeyIdentifier;
int valueIndex = isValue ? valueIdentifier : sValueIdentifier;
workingDictionary.Add( row[ keyIndex ].ToString(), row[ valueIndex ] );
}
Upvotes: 3
Reputation: 14039
if isKey and isValue are bool castable to int, force them in respective bits.
unsigned char sw_var = isKey + 2*isValue;
Then sw_var
is 0-3 depending on the booleans.
You can bind a number of bit fields that way:
unsigned long long bitfield =
key1 * (1ULL<<0)
+ key2 * (1ULL<<1)
+ key3 * (1ULL<<2)
...
+ key63 * (1ULL<<63);
(of course using all the resulting combinations a switch key would be extremely silly...)
Upvotes: 0
Reputation: 7430
The switch
statement is not a loop, it provides an alternative to using multiple if-else statements.
If you're asking can I use two variables in a switch statement, the answer is usually no but maybe you could combine the values to do something like in C#:
string sVal1 "abc", sVal2 = "xyz";
switch(sVal1 + "_" + sVal2)
{
case "abc_xyz":
// do something
break;
case "def_sdr":
// do something
break;
default:
// all else
break;
}
Most likely in your case you're going to need to use to if-else statements. A switch is not what you want.
Upvotes: 0
Reputation: 545528
That depends on the language – VB for example can theoretically do this, as can Ruby. For most other languages, one switch = one variable.
By the way, there’s no such thing as a “switch loop” (ignoring Duff’s device).
Upvotes: 4