how to evaluate ( math ) a string expression, vb.net - vb.net

I'm not sure the term I used is correct. but I have a string expression and I want it to be calculated.
this an example
Dim S = "4+4"
dim result = evaluate(S) 'some sort of treatment // that return 8
I'm not sure how this is going to work. I'm familiar with the JS eval function. but it seems that I need to add some sort of a library. and I don't want to do that.
I have found some links about using
dim s = new expression("4+4")
and getting the result with
s.evaluate()
but that require to add another library.
and as I said before I don't want to use any library.
I just want a solution on how to proceed? I have hit a wall.
BTW I'm still a beginner try to answer as simple as you can I would appreciate it.

You can use the DataTable.Compute-"trick":
Dim tbl = new DataTable()
Dim result = Convert.ToDouble(tbl.Compute("4+4", Nothing))
The following arithmetic operators are supported in expressions:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
More informations: DataColumn.Expression at Expression Syntax.

Related

VB.Net -" console.write(Format((87.20 \ 43.60))) " returning result of 1 not 2, why?

The below line of code is returning as a 1 instead of a 2, for reasons I can't comprehend.
console.write(Format((87.20 \ 43.60)))
Surely this should return the result of 2 but I've checked in another environment and it returns a can anyone tell me why?
I have tried putting the code into a second environment but the result was the same I don't understand why it is returning 1 instead of 2, can anyone enlighten me?
Thanks for the help but found the answer.
Decimals are converted to Long before Integer division and due to this are subject to banker's rounding, multiplying both numbers by a 100 before the operation resolves the issue.
Source of information:
Learn Microsoft - VB.Net - \ Operator - Remarks
Thanks,
While I am glad you resolved your own question, I did want to provide an alternative.
When you use the integer division operator, you do not have control as to how the rounding should occur. Whereas if you do a floating-point division operator you can keep the precision and then use one of the built-in Math class methods (documentation) to specify how the number should round.
Take a look at this example:
Dim result = 87.20 / 43.60
Dim roundUp = Math.Ceiling(result)
Dim roundDown = Math.Floor(result)
Dim bankersRounding = Math.Round(result)
Fiddle: https://dotnetfiddle.net/LZEMXV
Because in your example you are using Console.Write (which treats the data as a String) you do not need to cast the value to an Integer data type. However, if you needed the value as an Integer, any one of those variables outside result can be safely converted to an Integer using the Parse method (documentation).

Does the Unary Operators(++ or --) are allowed in vb.net? [duplicate]

I just saw some sample code that someone posted (here) that set an integer variable equal to ++1. I was shocked that the VB.NET compiler would accept that as valid syntax. For instance, this compiles:
Dim i As Integer = 0
i = ++1
i = ++1
Console.WriteLine(i) ' Outputs "1"
As best I can tell, it seems to ignore the pluses and just use the value that follows it. For instance:
Dim i As Integer = 0
i = ++10
Console.WriteLine(i) ' Outputs "10"
So my question is, why is that valid syntax? Is there some rule for the + operator that I'm totally unaware of. As far as I knew, that was invalid and ++ was not, itself, an operator in VB.NET.
Unlike in some other languages, it’s just a sign. Signs can be duplicated – +-++1 works, ---3 works, and Not Not Not Not condition works as well.

VB.Net Regular expression

I want to have a string in the following format
"FAG001 FAG002 FAG003"
and want to split it into
"FAG001"
"FAG002"
"FAG003"
using a regular expression. Unfortunately my knowledge of regular expression synatax is limited to say teh least. I have tried things like
Dim result = Regex.Split(npcCodes, "([A-Z]3[0-9]3)").ToList
without luck
No need of regex here, you could use String.Split
Dim result As String() = npcCodes.Split(new Char[]{" "})
But if you really want to use regex :
Dim result = Regex.Split(npcCodes, " ").ToList()
As madgnome has pointed out you don't need regular expressions here if the string is always separated with spaces.
However for your information the error you made was that you need curly braces for numeric quantifiers:
[A-Z]{3}
And instead of Regex.Split you can uses Regex.Matches.
The regular expression to use in the Split method would be really simple:
Dim result = Regex.Split(npcCodes, " ").ToList
As the expression only matches a single character, you can just as well use the regular Split method in the String class:
Dim result = npcCodes.Split(" "C).ToList

Do you choose Linq over Forloops?

Given a datatable containing two columns like this:
Private Function CreateDataTable() As DataTable
Dim customerTable As New DataTable("Customers")
customerTable.Columns.Add(New DataColumn("Id", GetType(System.Int32)))
customerTable.Columns.Add(New DataColumn("Name", GetType(System.String)))
Dim row1 = customerTable.NewRow()
row1.Item("Id") = 1
row1.Item("Name") = "Customer 1"
customerTable.Rows.Add(row1)
Dim row2 = customerTable.NewRow()
row2.Item("Id") = 2
row2.Item("Name") = "Customer 2"
customerTable.Rows.Add(row2)
Dim row3 = customerTable.NewRow()
row3.Item("Id") = 3
row3.Item("Name") = "Customer 3"
customerTable.Rows.Add(row3)
Return customerTable
End Function
Would you use this snippet to retrieve a List(Of Integer) containing all Id's:
Dim table = CreateDataTable()
Dim list1 As New List(Of Integer)
For i As Integer = 0 To table.Rows.Count - 1
list1.Add(CType(table.Rows(i)("Id"), Integer))
Next
Or rather this one:
Dim list2 = (From r In table.AsEnumerable _
Select r.Field(Of Integer)("Id")).ToList()
This is not a question about whether to type cast the Id column to Integer by using .Field(Of Integer), CType, CInt, DirectCast or whatever but generally about whether or not you choose Linq over forloops as the subject implies.
For those who are interested: I ran some iterations with both versions which resulted in the following performance graph:
graph http://dnlmpq.blu.livefilestore.com/y1pOeqhqQ5neNRMs8YpLRlb_l8IS_sQYswJkg17q8i1K3SjTjgsE4O97Re_idshf2BxhpGdgHTD2aWNKjyVKWrQmB0J1FffQoWh/analysis.png?psid=1
The vertical axis shows the milliseconds it took the code to convert the rows' ids into a generic list with the number of rows shown on the horizontal axis. The blue line resulted from the imperative approach (forloop), the red line from the declarative code (linq).
Whatever way you generally choose: Why do you go that way and not the other?
Whenever possible I favor the declarative way of programming instead of imperative. When you use a declarative approach the CLR can optimize the code based on the characteristics of the machine. For example if it has multiple cores it could parallelize the execution while if you use an imperative for loop you are basically locking this possibility. Today maybe there's no big difference but I think that in the future more and more extensions like PLINQ will appear allowing better optimization.
I avoid linq unless it helps readability a lot, because it completely destroys edit-and-continue.
When they fix that, I will probably start using it more, because I do like the syntax a lot for some things.
For almost everything I've done I've come to the conclusion that LINQ is optimized enough. If I handcrafted a for loop it would have better performance, but in the grand scheme of things we are usually talking milliseconds. Since I rarely have a situation where those milliseconds will make any kind of impact, I find it's much more important to have readable code with clear intentions. I would much rather have a call that is 50ms slower than have someone come along and break it altogether!
Resharper has a cool feature that will flag and convert loops into Linq expressions. I will flip it to the Linq version and see if that hurts or helps readability. If the Linq expression more clearly communicates the intent of the code, I will go with that. If the Linq expression is unreadable, I will flip back to the foreach version.
Most of the performance issues don't really compare with readability for me.
Clarity trumps cleverness.
In the above example, I would go with the the Linq version since it clearly explains the intent and also locks out people accidently adding side effects in the loop.
I recently found myself wondering whether I've been totally spoiled by LINQ. Yes, I now use it all the time to pick all sort of things out from all sort of collections.
I started to, but found out in some cases, I saved time by using this approach:
for (var i = 0, len = list.Count; i < len; i++) { .. }
Not necessarily in all cases, but some. Most extension methods use the foreach approach of querying.
I try to follow these rules:
Whenever I'm just querying (filtering, projecting, ...) collections, use LINQ.
As soon as I'm actually 'doing' something with the result (i.e, introduce side effects), I'll use a for loop.
So in this example, I'll use LINQ.
Also, I always try to split up the 'query definition' from the 'query evaluation':
Dim query = From r In table.AsEnumerable()
Select r.Field(Of Integer)("Id")
Dim result = query.ToList()
This makes it clear when that (in this case in-memory) query will be evaluated.

RegEx to get path of file, without domain

I'm new to regular expressions, and have no clue where to start, it's like a diff language to me. But I need one quick to accomplish a task.
I need to take
http://www.domain.com/folder1/folder2/file_path.txt
and get just
/folder1/folder2/file_path.txt
from it.
Thanks!
construct a URI object from it and one of the properties of it will have what you want.
I think that regex should work:
^http://.*?/(.*)$
(tested with Python)
Since VB.NET is in the tag for this question, I assume you have access at the server side to the Request object:
Dim instance As HttpRequest
Dim value As String
value = instance.Path
This should give you exactly what you asked for.
Edit: On second thought - you could be parsing URLs from some input string... in which case, regex will only help if you have a simple (regular) set of inputs:
Do you know all the possible domains? i.e. are "http://www.ABC.com" and "http://www.DEF.com" the only possible domains?
Then here:
Dim text As String = "http://www.ABC.com/folder1/folder2/file.txt"
Dim pattern As String = "(?:http://www.ABC.com|http://www.DEF.com)(.*)"
Dim r As Regex = new Regex(pattern, RegexOptions.IgnoreCase)
' Match the regular expression pattern against a text string.
Dim m As Match = r.Match(text)
Dim g as Group = m.Groups(2) 'Gives the string matched by the capturing parentheses
Supporting more protocols and making the protocol optional too.
((https?|ftp)://)?(.*?)/(.*)