Confused with conditional and logical operators - VB.net - vb.net

I'm kind of new to VB.net, and since I just finished a C# course, the lack of parentheses creates a lot of confusion on how to write certain combinations of operators.
The C# equivalent of the line I am trying to reproduce in VB would be like this :
if ( (a == 0 && b != null) || (a == 1 && c != null) )
I'm have no idea how to write this in VB, I've tried many combinations of And, Or, AndAlso, OrElse, etc. but I can't achieve the desired result.
I can't find any clear example of C# v.s. VB.net comparison on operators, and the notes I have aren't helpful either.
Can someone help me figure this out?

The equals operator is == in C# and = in VB.
if ( (a == 0 && b != null) || (a == 1 && c != null) )
statement; // One single statement only
or
if ( (a == 0 && b != null) || (a == 1 && c != null) ) {
statement; // Any number of statements
}
This online conversion tool will convert it to VB for you:
If (a = 0 AndAlso b IsNot Nothing) OrElse (a = 1 AndAlso c IsNot Nothing) Then
statement
End If
C# && translates to AndAlso in VB.
C# || translates to OrElse in VB.
With these operators the evaluation stops as soon as the result is determined. This is known as "short-circuit" evaluation. E.g. in a && b the result is known to be false if a is false, and b will not be evaluated. This is especially important when the evaluation has side effects, like performing database queries, raising events or modifying data. It is also useful in conditions like these person != null && person.Name == "Doe" where the second would throw an exception if the first term evaluates to false.
The equivalent of the VB And and Or Boolean operators that do not use short-circuit evaluation are & and | in C#. Here all the terms will always be evaluated.
If (a = 0 Or b = 0 And c = 0) Then
statement
End If
if (a = 0 | b = 0 & c = 0) {
statement;
}

The vb.net equivalent would be
If (a = 0 AndAlso b IsNot Nothing) OrElse (a = 1 AndAlso c IsNot Nothing ) Then
Note in c#, it should be a == 0 and not a = 0
Checkout this post with a comprehensive comparison.

if ( (a = 0 && b != null) || (a = 1 && c != null) )
Is equivilent to:
if ( ( a = 0 AndAlso b IsNot Nothing) OrElse (a = 1 AndAlso c IsNot Nothing) )

Related

Lua while loop with multiple conditions

while (cyclesc > 0) and (FC = 1 or FC = 3 or FC = 4) do
--dostuff
end
Lua 101 or even coding 101 I'm sure so forgive me - what is best way to write this - nested while loops? seems a waste - is there a way to have multiple conditions in one line of a while loop?
In your example, you've got
while (cyclesc > 0) and (FC = 1 or FC = 3 or FC = 4) do
--dostuff
end
which almost works, but you've used = instead of ==. = is the variable assignment operator, and == compares two values.
Your code should be
while (cyclesc > 0) and (FC == 1 or FC == 3 or FC == 4) do
--dostuff
end
Community wiki as this was solved in the comments

Convert the string to the equivalent hex of that string

I would like to convert the string that I've inputted to it's equivalent hex.
For example:
I have the string D7 and I would like it to be converted to hex D7 so that it can be read by the software that can only read hex values.
bla-bla-bla = Error, because there's no hex equivalent of it
aBc = ABC because there's a hex equivalent of it.
123 = 123 because there's a hex equivalent of it.
12 AB 3.14 = Error, because there's no hex equivalent of it
3.F1 = Error, because there's no hex equivalent of it
Though I'm not sure about that, but I guess that will be the result. As long as there's no hex equivalent of each text then it will be error.
Edit: I've tried to convert the C# code of Dmitry, but it is still not working. I'll try it again on Monday
Here's the code
Dim source As String = "abc789Def"
Dim Sb As New StringBuilder(source.Length)
For Each c As Char In source
If ((c >= "0" AndAlso c <= "9") Or (c >= "a" AndAlso c <= "f") Or (c >= "A" AndAlso c <= "F")) Then
Sb.Append(Char.ToUpper(c))
Dim result As String = Sb.ToString
Console.WriteLine("result " & result)
Else
Console.Write("Error")
End If
Next
It seems, that you want to have the string to be in upper case if all the characters in it are in either ['0'..'9'] or ['a'..'f'] or ['A'..'F'] range (C# code):
String source = "abc789Def";
if (source.All(c => (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F'))) {
String result = source.ToUpper();
//TODO: put a relevant code here
}
else {
// error: at least one character can't be converted
}
Edit: no Linq solution:
String source = "abc789Def";
StringBuilder Sb = new StringBuilder(source.Length);
foreach (Char c in source)
if ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F'))
Sb.Append(Char.ToUpper(c));
else {
// Error: at least one character can't be converted
return;
}
String result = Sb.ToString();
// Put relevant code here
The ability to validate a Hex number is provided by the TryParse method on integer types using the System.Globalization.NumberStyles.HexNumber style.
Dim inputValue As String = "23"
Dim returnValue As String = Nothing
If ValidateAndFormatHex(inputValue, returnValue) Then
Console.WriteLine(returnValue)
Else
Console.WriteLine("Error")
End If
Private Shared Function ValidateAndFormatHex(input As String, ByRef formattedValue As String) As Boolean
input = input.Trim().ToUpperInvariant
Dim result As Int32
Dim parses As Boolean = Int32.TryParse(input, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, result)
If parses Then formattedValue = input
Return parses
End Function

If Else Statement in vb.Net

I wanted to have this condition like i have b2.text, c3.text, d4.text, e5.text, f6.text, g7.text, h8.text, i9.text and j10.text.
And if they are all equal to zero then statement else continue.
i tried
If (b2.Text = 0 & c3.Text = 0 & d4.Text = 0 & e5.Text = 0 & f6.Text = 0 & g7.Text = 0 & h8.Text = 0 & i9.Text = 0 & j10.Text = 0) Then
a1.Text = 10000000
Else
Msgbox.Show("Cannot sort")
End if
Unfortunately i remembered & function only accept two variable only :P
How can i do it?
Thank you
You don't want & for VB, you want AndAlso. And while it is probably a bit above your level, you might want to look into Linq.
If ({b2.Text, c3.Text, d4.Text, e5.Text, f6.Text, g7.Text, h8.Text, i9.Text, j10.Text}).All(Function(f) f = "0") Then
a1.Text = 10000000
Else
Msgbox.Show("Cannot sort")
End IF
As others have said, you should turn on Option Strict, so that your comparison to an int gets flagged. I made the string "0" above, but you could easily modify it to use length if that is what you actually need.
I don't know what language are you using but I'm pretty sure you can compare more than 2 values The solution may be like this.
if (b2.text == 0 && c3.text == 0 && d4.text == 0 && e5.text== 0 && f6.text == 0 && g7.text == 0 && h8.text == 0 && i9.text == 0 && j10.text == 0) {
// when conditions are true
}
else {
// else code here
}

Which points are co-linear & in sequence (i.e. which two points I am between)

I have longitude and latitude of my position, and I have a list of positions that is ordered as a list of points(long/lat)) along a road. How do I find out which two points I am between?
If I just search for the two nearest points I will end up with P2 and P3 in my case in the picture.
I want to know how to find out that I'm between point p1 and p2.
The list of points I will search will be database rows containing latitude and longitude so pointers to how to build the sql-query, linq-query or pseudo code, everything that points me to the best solution is welcome. I'm new to geolocation and the math around it so treat me as an newbie. ;)
(The list of points will be ordered so P1 will have an id of 1, p2 will have an id of 2 and so on. )
Bear in mind that what you propose might become really complex (many points under equivalent conditions) and thus delivering an accurate algorithm would require (much) more work. Taking care of simpler situations (like the one in your picture) is not so difficult; you have to include the following:
Convert latitude/longitude values into cartesian coordinates (for ease of calculations; although you might even skip this step). In this link you can get some inspiration on this front; it is in C#, but the ideas are clear anyway.
Iterate through all the available points "by couples" and check whether the point to be analysed (Mypos), falls in the line formed by them, in an intermediate position. As shown in the code below, this calculation is pretty simple and thus you don't need to do any pre-filtering (looking for closer points before).
.
Dim point1() As Double = New Double() {0, 0} 'x,y
Dim point2() As Double = New Double() {0, 3}
Dim pointToCheck() As Double = New Double() {0.05, 2}
Dim similarityRatio As Double = 0.9
Dim minValSimilarDistance As Double = 0.001
Dim similarityDistance As Double = 0.5
Dim eq1 As Double = (point2(0) - point1(0)) * (pointToCheck(1) - point1(1))
Dim eq2 As Double = (point2(1) - point1(1)) * (pointToCheck(0) - point1(0))
Dim maxVal As Double = eq1
If (eq2 > eq1) Then maxVal = eq2
Dim inLine = False
Dim isInBetween As Boolean = False
If (eq1 = eq2 OrElse (maxVal > 0 AndAlso Math.Abs(eq1 - eq2) / maxVal <= (1 - similarityRatio))) Then
inLine = True
ElseIf (eq1 <= minValSimilarDistance AndAlso eq2 <= similarityDistance) Then
inLine = True
ElseIf (eq2 <= minValSimilarDistance AndAlso eq1 <= similarityDistance) Then
inLine = True
End If
If (inLine) Then
'pointToCheck part of the line formed by point1 and point2, but not necessarily between them
Dim insideX As Boolean = False
If (pointToCheck(0) >= point1(0) AndAlso pointToCheck(0) <= point2(0)) Then
insideX = True
Else If (pointToCheck(0) >= point2(0) AndAlso pointToCheck(0) <= point1(0)) Then
insideX = True
End If
if(insideX) Then
If (pointToCheck(1) >= point1(1) AndAlso pointToCheck(1) <= point2(1)) Then
isInBetween = True
ElseIf (pointToCheck(1) >= point2(1) AndAlso pointToCheck(1) <= point1(1)) Then
isInBetween = True
End If
End If
End If
If (isInBetween) Then
'pointToCheck is between point1 and point2
End If
As you can see, I have included various ratios allowing you to tweak the exact conditions (the points will, most likely, not be falling exactly in the line). similarityRatio accounts for "equations" being more or less similar (that is, X and Y values not exactly fitting within the line but close enough). similarityRatio cannot deal properly with cases involving zeroes (e.g., same X or Y), this is what minValSimilarDistance and similarityDistance are for. You can tune these values or just re-define the ratios (with respect to X/Y variations between points, instead of with respect to the "equations").
An equivalent solution in Scala for clarity:
def colinearAndInOrder(a: Point, b: Point, c: Point) = {
lazy val colinear: Boolean =
math.abs((a.lng - b.lng) * (a.lat - c.lat) -
(a.lng - c.lng) * (a.lat - b.lat)) <= 1e-9
lazy val bounded: Boolean =
((a.lat < b.lat && b.lat < c.lat) || (a.lat > b.lat && b.lat > c.lat)) &&
((a.lng < b.lng && b.lng < c.lng) || (a.lng > b.lng && b.lng > c.lng))
close(a,b) || close(b,c) || (colinear && bounded)
}
def close(a: Point, b: Point): Boolean = {
math.abs(a.lat - b.lng) <= 1e-4 && math.abs(a.lat - b.lng) <= 1e-4
}

Multiple Conditionals in Poly ML

If, for example, I wanted to define a function that returned true if a=b and b=c, and false if neither one of those equalities were true in Poly ML, how would I write it? I'm not sure how to do more than one conditional simultaneously.
Isn't
a = b andalso b = c
what you want?
I believe this does what you need:
fun f (a, b, c) =
if a = b andalso b = c
then true
else
if a <> b andalso b <> c
then false
else ... (* you haven't specified this case *)
The main points here are:
You can nest conditionals, i.e. have one if expression inside another's then or else case
The operator andalso is the boolean conjunction, meaning x andalso y is true if and only if x evaluates to true and y evaluates to true.
You can put this more concisely using a case expression:
fun f (a, b, c) =
case (a = b, b = c) of
(true, true) => true
| (false, false) => false
| _ => (* you haven't specified this case *)