Is it possible to do one line if statement in VB .NET? If so, how?
Use IF().
It is a short-circuiting ternary operator.
Dim Result = IF(expression,<true return>,<false return>)
SEE ALSO:
IIF becomes If, and a true ternary operator
Is there a conditional ternary
operator in VB.NET?
Orcas introduces the IF operator - a
new and improved IIF
The Ternary Operator in VB.NET
It's actually pretty simple..
If CONDITION Then ..INSERT CODE HERE..
Single line
Syntax:
If (condition) Then (do this)
Example:
If flag = true Then i = 1
Multiple ElseIf's
Syntax:
If (condition) Then : (do this)
ElseIf (condition2) Then : (do this)
Else : (do this)
End If
OR
If (condition) Then : (do this) : ElseIf (condition2) Then : (do this) : Else : (do this) : End If
Multiple operations
Syntax:
If (condition) Then : (do this) : (and this) : End If
At the risk of causing some cringing by purests and c# programmers, you can use multiple statements and else in a one-line if statement in VB. In this example, y ends up 3 and not 7.
i = 1
If i = 1 Then x = 3 : y = 3 Else x = 7 : y = 7
Or
IIf(CONDITION, TRUE_ACTION, FALSE_ACTION)
Just add Then:
If A = 1 Then A = 2
or:
If A = 1 Then _
A = 2
One Line 'If Statement'
Easier than you think, noticed no-one has put what I've got yet, so I'll throw in my 2-cents.
In my testing you don't need the continuation? semi-colon, you can do without, also you can do it without the End If.
<C#> = Condition.
<R#> = True Return.
<E> = Else Return.
Single Condition
If <C1> Then <R1> Else <E>
Multiple Conditions
If <C1> Then <R1> Else If <C2> Then <R2> Else <E>
Infinite? Conditions
If <C1> Then <R1> Else If <C2> Then <R2> If <C3> Then <R3> If <C4> Then <R4> Else...
' Just keep adding "If <C> Then <R> Else" to get more
-Not really sure how to format this to make it more readable, so if someone could offer a edit, please do-
If (X1= 1) Then : Val1= "Yes" : Else : Val1= "Not" : End If
You can use the IIf function too:
CheckIt = IIf(TestMe > 1000, "Large", "Small")
Its simple to use in VB.NET code
Basic Syntax
IIF(Expression as Boolean,True Part as Object,False Part as Object)As Object
Using IIF same as Ternary
Dim myVariable as string= " "
myVariable = IIf(Condition, True,False)
If (condition, condition_is_true, condition_is_false)
It will look like this in longer version:
If (condition_is_true) Then
Else (condition_is_false)
End If
Related
I'm trying to conditionally add a part to my SQL query using Exposed's DAO API. My goal is to have:
SELECT * FROM table
WHERE column1 = 1
AND column2 = $value
AND column3 = 3
where the existence of the AND column2 = $value part depends on a filter.
I've tried with:
TableDAO.find {
Table.column1 eq 1 and (
when (filter.value) {
null -> null // Type mismatch. Required: Expression<Boolean>. Found: Op<Boolean>?
else -> Table.column2 eq filter.value
}) and (
Table.column3 = 3
)
}.map { it.toModel() }
but I can't find a way to return an empty expression or somehow exclude that part from the query. The only solution I can make work is something like
null -> Table.column2 neq -1
but I feel like there should be a better way.
You'll have to assign your expressions into a local variable:
var expr = Table.column1 eq 1
if(filter.value) {
expr = expr and (Table.column2 eq filter.value)
}
expr = expr and (
Table.column3 = 3
)
I don't have my IDE in front of me, but this is the general idea. You can try to figure out something clever, but it would make your code unnecessarily complex.
I was making a calculator in Kotlin and I'm having trouble solving an issue that I'm having with while().On this particular part of the code, I'm trying to find the first operator in the equation, but I need to exclude the ones that indicate whether a number is negative - (or positive +, optional), which need to be indicated between parentheses like so: (-5)
var charay = charArrayOf('+', '-', '*', '/')
var op = 0
var reference = 0
var bol = false
while( bol == false && op != -1){
println(op)
println(bol)
println(bol == false && op != -1)
op = input.indexOfAny(charay, reference)
if (!input.get(op - 1).equals('(')){
bol = true
}else{
reference = op + 1
}
println(op)
println(bol)
println(bol == false && op != -1)
}
To test a normal equation I entered the equation 4+4 and the console looks like this:
0
false
true
1
true
false
0
false
true
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -2
at java.lang.String.charAt(String.java:658)
at CalculatorKt.CalculateValue(Calculator.kt:67)
at CalculatorKt.CalculateValue(Calculator.kt:108)
at CalculatorKt.main(Calculator.kt:119)
Like I suspected, for some reason, the variables reset at the end of the while(), which is the reason why it never leaves said while(). Can anyone tell me why?
Read the error. You're trying to read the character of a string at an index that doesn't exist with this statement:
input.get(op - 1)
You need to check what op is first to make sure it is found. indexOfAny returns -1 if not found in the string. Because we can't see what charay is, we can't help you further.
I am having some issue with sql... Below have a working and not working example. I hard coded them so its easier to see.
$deleteData = $con->prepare("DELETE FROM markers WHERE sid=? AND user_id=? AND lat=? AND lng=?");
$deleteData->bind_param("iidd", $sid, $user_id,$lat,$lng);
$sid= '239';
$user_id = '2';
$lat = '39.724869';
$lng = '-91.400116';
$deleteData -> execute();
Some reason when I attempt to delete using type double in bind_param just doesn't work. Any suggestions? I changed it with or without '' around the lat lng, still doesn't work.
If I change it to below, it deletes just fine.
$deleteData = $con->prepare("DELETE FROM markers WHERE sid=? AND user_id=?);
$deleteData->bind_param("ii", $sid, $user_id);
$sid= '239';
$user_id = '2';
$deleteData -> execute();
First of all you have a syntax error in the second example (missing character ").
Also you did not assigned $sid variable.
Then I have a little bit stupid question. Are you aware, that assign of variables $blog_id, $user_id ... etc. must be before call of method $deleteData->bind_param()?
And also, don't forget that when you are comparing 2 real values, then you should also add some tolerance, so try instead:
$deleteData = $con->prepare("DELETE FROM markers WHERE sid=? AND user_id=? AND ABS(lat - ?) < 0.0000001 AND ABS(lng - ?) < 0.0000001");
Replace $blog_id = '239';with $sid = '239'; since that's the variable name you use in the bind_param() statement.
Trying to construct a query such that I have multiple statement specifying joins, each with a where message chained onto them. When the query is run, I get all the joins, but only the where from my first call. Here's the method body that's doing the query:
observations_joins = Observation.joins(:obs_session => :project).where(:obs_sessions=>{:project_id=>self.project.id})
descriptor_hash = descriptor_where_hash if tag_descriptors && tag_descriptors.size > 0
puts "The descriptor_hash: #{descriptor_hash}"
observations = observations_joins.joins(:obs_descriptors).where("#{descriptor_hash['query_string']}", descriptor_hash['match_values']) if tag_descriptors && tag_descriptors.size > 0
arel = observations.arel
puts "The arel sql should be: #{arel.to_sql}"
observations
I have another method that gets called from inside the second joins statement, that iterates over the potential match values and generates the string and the values used; body here:
match_values = []
query_string = "obs_descriptors.tag_name = ?"
tag_descriptors.each_index do |index|
query_string = query_string + " #{tag_descriptors.fetch(index).qualifier_key} obs_descriptors.tag_name = ?" if index != 0
match_values << tag_descriptors.fetch(index).tag_name
end
{:match_values=>match_values, :query_string=>query_string}
So the sql getting generated looks like:
SELECT `observations`.* FROM `observations` INNER JOIN `obs_sessions` ON `obs_sessions`.`id` = `observations`.`obs_session_id` INNER JOIN `projects` ON `projects`.`id` = `obs_sessions`.`project_id` INNER JOIN `obs_descriptors` ON `obs_descriptors`.`observation_id` = `observations`.`id` WHERE (`obs_sessions`.`project_id` = 1)
and doesn't include the second set of where conditions. I also print the hash, just to make sure I'm not losing my mind and there are values in there, and there indeed are.
So, what am I missing to make this go as I'd expect it to?
Answering my own question here. The most elegant, concise way I found to get this working was to drop down to arel directly. Also, there were some issues with the original code posted, but even still, I needed to use arel to get properly grouped conditions. For context, I've got an object that, based on it's related data, needs to dynamically construct a semi advanced query, so I wanted to do things like checking for the existence of certain related data, and if present, then tack on the additional joins and wheres. Here's the final versions of the relevant methods:
def find_observations
observations = Observation.select('distinct observations.*').includes(:obs_session).includes(:judgements).includes(:concepts).includes(:obs_descriptors)
observations = observations.joins(:obs_session => :project).where(:obs_sessions=>{:project_id=>self.project.id})
if tag_descriptors && tag_descriptors.size > 0
observations = observations.where(descriptor_predicate)
end
if session_descriptors && session_descriptors.size > 0
observations = observations.where(session_predicate)
end
if user_descriptors && user_descriptors.size > 0
observations = observations.where(user_predicate)
end
#puts "observations sql is: #{observations.to_sql}"
observations.all
end
The above method optionally calls the remaining methods, which return the arel used in the where calls when chaining the AR object while building up the eventual query. Notice the disctinct; I'd had a version of this using arel entirely, that appeared to be working, but was in fact returning duplicates. I found references to using group(some_attribute) to fake things, but that turned out to cause problems down the chain, so to speak. So I fell back to using ActiveRelation to specify the distinct, joins and includes, and arel for the rest.
The next one was the part that was originally giving me lots of trouble; there are a variable number of possibilities, and each one could be either an AND or OR condition, and needed to be grouped separately so as not to mess up the rest of the generated where clause.
def descriptor_predicate
od = Arel::Table.new :obs_descriptors
predicate = nil
self.tag_descriptors.each_index do |index|
descriptor = self.tag_descriptors.fetch(index)
qual_key = descriptor.qualifier_key
tag_name = descriptor.tag_name
if index == 0
predicate = od[:descriptor].eq(tag_name)
else
if qual_key == "OR"
predicate = predicate.or(od[:descriptor].eq(tag_name))
else
predicate = predicate.and(od[:descriptor].eq(tag_name))
end
end
end
predicate
end
And finally the other predicate methods for the potential joined entity values:
def session_predicate
o = Arel::Table.new :observations
predicate = nil
self.session_descriptors.each_index do |index|
obs = self.session_descriptors.fetch(index)
if index == 0
predicate = o[:obs_session_id].eq(obs.entity_id)
else
predicate = predicate.or(o[:obs_session_id].eq(obs.entity_id))
end
end
predicate
end
def user_predicate
o = Arel::Table.new :observations
predicate = nil
self.user_descriptors.each_index do |index|
obs = self.user_descriptors.fetch(index)
if index == 0
predicate = o[:contributor_id].eq(obs.entity_id)
else
predicate = predicate.or(o[:contributor_id].eq(obs.entity_id))
end
end
predicate
end
def descriptor_where_string(included_where_statements)
tag_descriptors.each_index do |index|
qual_key = tag_descriptors.fetch(index).qualifier_key
tag_name = tag_descriptors.fetch(index).tag_name
if index == 0
query_string = "obs_descriptors.descriptor = #{tag_name}"
else
if qual_key == "OR"
query_string = query_string + " #{qual_key} obs_descriptors.descriptor = #{tag_name} AND #{included_where_statements} "
else
query_string = query_string + " #{qual_key} obs_descriptors.descriptor = ?"
end
end
end
query_string
end
Ultimately, I found the best solution involved leveraging both ActiveRelation chaining for providing the distinct and includes, and using arel directly for the conditions on the related values. Hope this helps somebody at some point.
In an rdlc report I want to compare integers like
if(expression)
{
// do something
}
else if(expression)
{
// do something else
}
What is the syntax for this?
Rather than using nested IIF statements I prefer the Switch statement.
From the MSDN...
=Switch(
Fields!PctComplete.Value >= 10, "Green",
Fields!PctComplete.Value >= 1, "Blue",
Fields!PctComplete.Value = 1, "Yellow",
Fields!PctComplete.Value <= 0, "Red"
)
Hope it helps :)
You will have to nest IIF statements like this:
= IIF (expression = 1, "Is 1", IIF (expression = 2, "Is 2"))
Use switch instead. I know I reached late here,but hope that it may help someone.
=Switch(Fields!Parameter.value = 2,"somethingnew", 1=1 ,"somethingelse")
1=1 refers to default in switch case.
It is similar like
if(Parameter.Value == 2)
{
somethingnew
}
else
{
somethingelse
}
This is the Syntax for your requirement:
=IIf(CInt(Fields!expression1.value)==1,true,IIf(Cint(Fields!expression2.value)==2,true,nothing))
In true part you can specify the statement to be executed.
In addition to what has been said, the If(condition, true_part, false_part) ternary operator should (with one I) be preferred over the IIf(condition, true_part, false_part) function (with two I's) in most cases.
The If() ternary operator will short-circuit evaluate only the part that corresponds to condition outcome (e.g. a condition that is True will only evaluate the true_part).
The IIf() function will always evaluate the condition and both parts, because it is just a function call and all parameters of the function will be evaluated before the call.
Since developers usually expect short-circuit evaluation in IF statements, the usage of the If() ternary operator should be the default choice.
It allows you to run expressions that check for Nothing, like the following, which would not work without lazy evaluation:
=If(Fields!Blog.Value IsNot Nothing, Fields!Blog.Value.Name, "Blog is missing")
You could also try this example
= IIF(Parameters!expression.Value = True, 'somethingnew', 'somethingelse')