setting strings_array(0) = "" problem - vb.net

im getting an exception on this:
Dim strings_extreme As String()
strings_extreme(0) = ""
it says that i am using it before it is being assigned a value
how do i initialize it?
please note that i need to be able to do this:
strings_extreme = input.Split(","c).Distinct().OrderBy(Function(s) s)

If you truly don't know how many strings there are going to be, then why not just use an IList:
Dim stringList As IList(Of String) = New List(Of String)
stringList.Add("")
You can get the Count of how many strings there are and you can For Each through all the strings in the list.
EDIT: If you're just trying to build an array from a Split you should be able to do this:
Dim strings_extreme() As String = input.Split(...)

Dim strings_extreme As List(Of String) = New List(Of String)
strings_extreme.Add("value1")
strings_extreme.Add("value 2")
strings_extreme.Add("value 3rd")
strings_extreme.Add("value again")
Dim strings() As String = strings_extreme.ToArray()
...

Dim strings_extreme(10) As String
strings_extreme(0) = ""
Further info: http://www.startvbdotnet.com/language/arrays.aspx

Dim strings_extreme as String() = {"yourfirstitem"}
But actually, why not take a look at some more advanced data structure from System.Collections namespace?

Shouldn't bother setting a string to "".
Try using:
Dim strings_extreme(10) As String
strings_extreme(yourIndex) = String.Empty

Related

List(of String) or Array or ArrayList

Hopefully a simple question to most programmers with some experience.
What is the datatype that lets me do this?
Dim lstOfStrings as *IDK*
Dim String0 As String = "some value"
Dim String1 As String = "some value"
Dim String2 As String = "some value"
Dim String3 As String = "some value"
Dim String4 As String = "some value"
Dim String5 As String = "some value"
lstOfStrings.add(String0, String1, String2, String3)
I would access these like this
Dim s1 = lstOfStrings(0)
Dim s2 = lstOfStrings(1)
Dim s3 = lstOfStrings(2)
Dim s4 = lstOfStrings(3)
if I use List(of String)
I am only able to .add one thing to the list (at a time), and in my function I want to be able to store several values(at a time).
Solution:
Private Function Foo() As List(Of String)
Dim temp1 As String
Dim temp2 As String
Dim temp3 As String
Dim temp4 As String
Dim temp5 As String
Dim temp6 As String
Dim inputs() As String = {temp1, temp2, temp3, temp4, temp5, temp6}
Dim lstWriteBits As List(Of String) = New List(Of String)(inputs)
Return lstWriteBits
End Function
List(Of String) will handle that, mostly - though you need to either use AddRange to add a collection of items, or Add to add one at a time:
lstOfString.Add(String1)
lstOfString.Add(String2)
lstOfString.Add(String3)
lstOfString.Add(String4)
If you're adding known values, as you show, a good option is to use something like:
Dim inputs() As String = { "some value", _
"some value2", _
"some value3", _
"some value4" }
Dim lstOfString as List(Of String) = new List(Of String)(inputs)
' ...
Dim s3 = lstOfStrings(3)
This will still allow you to add items later as desired, but also get your initial values in quickly.
Edit:
In your code, you need to fix the declaration. Change:
Dim lstWriteBits() As List(Of String)
To:
Dim lstWriteBits As List(Of String)
Currently, you're declaring an Array of List(Of String) objects.
You can do something like this,
Dim lstOfStrings As New List(Of String) From {"Value1", "Value2", "Value3"}
Collection Initializers
Neither collection will let you add items that way.
You can make an extension to make for examle List(Of String) have an Add method that can do that:
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
For Each s As String In values
list.Add(s)
Next
End Sub
End Module
Now you can add multiple value in one call:
Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)
look to the List AddRange method here
Sometimes I don't want to add items to a list when I instantiate it.
Instantiate a blank list
Dim blankList As List(Of String) = New List(Of String)
Add to the list
blankList.Add("Dis be part of me list") 'blankList is no longer blank, but you get the drift
Loop through the list
For Each item in blankList
' write code here, for example:
Console.WriteLine(item)
Next
You can use IList(Of String) in the function :
Private Function getWriteBits() As IList(Of String)
Dim temp1 As String
Dim temp2 As Boolean
Dim temp3 As Boolean
'Pallet Destination Unique
Dim temp4 As Boolean
Dim temp5 As Boolean
Dim temp6 As Boolean
Dim lstWriteBits As Ilist = {temp1, temp2, temp3, temp4, temp5, temp6}
Return lstWriteBits
End Function
use
list1.AddRange(list2) to add lists
Hope it helps.
For those who are stuck maintaining old .net, here is one that works in .net framework 2.x:
Dim lstOfStrings As New List(of String)( new String(){"v1","v2","v3"} )

Convert string array to int array

I have tried a couple different ways and cannot seem to get the result I want using vb.net.
I have an array of strings. {"55555 ","44444", " "}
I need an array of integers {55555,44444}
This is a wpf page that is sending the array as a parameter to a crystal report.
Any help is appreciated.
You can use the List(Of T).ConvertAll method:
Dim stringList = {"123", "456", "789"}.ToList
Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str))
or with the delegate
Dim intList = stringList.ConvertAll(AddressOf Int32.Parse)
If you only want to use Arrays, you can use the Array.ConvertAll method:
Dim stringArray = {"123", "456", "789"}
Dim intArray = Array.ConvertAll(stringArray, Function(str) Int32.Parse(str))
Oh, i've missed the empty string in your sample data. Then you need to check this:
Dim value As Int32
Dim intArray = (From str In stringArray
Let isInt = Int32.TryParse(str, value)
Where isInt
Select Int32.Parse(str)).ToArray
By the way, here's the same in method syntax, ugly as always in VB.NET:
Dim intArray = Array.ConvertAll(stringArray,
Function(str) New With {
.IsInt = Int32.TryParse(str, value),
.Value = value
}).Where(Function(result) result.IsInt).
Select(Function(result) result.Value).ToArray
You can use the Array.ConvertAll method:
Dim arrStrings() As String = {"55555", "44444"}
Dim arrIntegers() As Integer = Array.ConvertAll(arrStrings, New Converter(Of String, Integer)(AddressOf ConvertToInteger))
Public Function ConvertToInteger(ByVal input As String) As Integer
Dim output As Integer = 0
Integer.TryParse(input, output)
Return output
End Function
Maybe something like this:
dim ls as new List(of string)()
ls.Add("55555")
ls.Add("44444")
ls.Add(" ")
Dim temp as integer
Dim ls2 as List(Of integer)=ls.Where(function(x) integer.TryParse(x,temp)).Select(function(x) temp).ToList()
Maybe a few more lines of code than the other answers but...
'Example assumes the numbers you are working with are all Integers.
Dim arrNumeric() As Integer
For Each strItemInArray In YourArrayName
If IsNumeric(strItemInArray) Then
If arrNumeric Is Nothing Then
ReDim arrNumeric(0)
arrNumeric(0) = CInt(strItemInArray)
Else
ReDim Preserve arrNumeric(arrNumeric.Length)
arrNumeric(arrNumeric.Length - 1) = CInt(strItemInArray)
End If
End If
Next
My $.02
Dim stringList() As String = New String() {"", "123", "456", "789", "a"}
Dim intList() As Integer
intList = (From str As String In stringList
Where Integer.TryParse(str, Nothing)
Select (Integer.Parse(str))).ToArray
Everything is much easier ))
Dim NewIntArray = YouStringArray.Select(Function(x) CInt(x)).ToArray

Splitting a CSV Visual basic

I have a string like
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
in a file
in two separate lines. I am reading it from the textbox. I have to output ab563372363_C/R and ab563372356_C/R in a text box. I am trying to use the split function for that but its not working..
Dim splitString as Array
results = "test.txt"
Dim FileText As String = IO.File.ReadAllText(results) 'reads the above contents from file
splitString = Split(FileText, ",", 14)
TextBox2.text = splitString(1) & splitString(13)
for the above code, it just prints the whole thing.. What's wrong?
Try this
Private Function GetRequiredText() As List(Of String)
Dim requiredStringList As New List(Of String)
Dim file = "test.txt"
If FileIO.FileSystem.FileExists(file) Then
Dim reader As System.IO.StreamReader = System.IO.File.OpenText(file)
Dim line As String = reader.ReadLine()
While line IsNot Nothing
requiredStringList.Add(line.Split(",")(1))
line = reader.ReadLine()
End While
reader.Close()
reader.Dispose()
End If
Return requiredStringList
End Function
This will read the file line by line and add the item you require to a list of strings which will be returned by the function.
Returning a List(Of String) may be overkill, but it's quite simple to illustrate and to work with.
You can then iterate through the list and do what you need with the contents of the list.
Comments welcome!!
Also this might work...
Dim query = From lines In System.IO.File.ReadAllLines(file) _
Select lines.Split(",")(1)
this will return an IEnumerable(Of String)
Enjoy
First
Since you are reading the whole text, your FileText would be ending like this:
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132,460
\r\n
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
So when you are referencing to your splitStringwith those indexes (1, 13) your result might probably be wrong.
Second
Try to specify what kind of type your array is, Dim splitString as Array should be Dim splitString As String()
Third
Make your code more readable/maintainable and easy to edit (not only for you, but others)
The Code
Private const FirstIndex = 1
Private const SecondIndex = 12
Sub Main
Dim myDelimiter As Char
Dim myString As String
Dim mySplit As String()
Dim myResult1 As String
Dim myResult2 As String
myDelimiter = ","
myString += "Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460"
myString += "Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455"
mySplit = myString.Split(myDelimiter)
myResult1 = mySplit(FirstIndex)
myResult2 = mySplit(SecondIndex)
Console.WriteLine(myResult1)
Console.WriteLine(myResult2)
End Sub

Deserializing json array into .net class

I'm having problems deserializing some json data, getting InvalidCastExceptions and the like.
Can anyone point me in the right direction?
Here's the json i'm wanting to deserialize;
[{"OrderId":0,"Name":"Summary","MaxLen":"200"},{"OrderId":1,"Name":"Details","MaxLen":"0"}]
Here's my code;
Public Class jsTextArea
Public OrderId As Integer
Public Name As String
Public MaxLen As String
End Class
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim rawdata = js.DeserializeObject(textAreaJson)
Dim lstTextAreas As List(Of jsTextArea) = CType(rawdata, List(Of jsTextArea))
OrderId is an Int in your json (note the lack fo quotes round the values), but you're declaring it as String in "jsTextArea". Also, unless the type that rawdata is returned as has a cast to List(Of jsTextArea), which it probably doesn't the code you've shown won't work.
Update
To get the data out into a List(Of jsTextArea) try the following:
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim lstTextAreas = js.Deserialize(Of List(Of jsTextArea))(textAreaJson)
Doing it all on one line worked a treat;
Dim lstTextAreas As List(Of jsTextArea) = js.Deserialize(textAreaJson, GetType(List(Of jsTextArea)))
Dim textAreaJson As String = "[{""OrderId"":0,""Name"":""Summary"",""MaxLen"":""200""},{""OrderId"":1,""Name"":""Details"",""MaxLen"":""0""}]"
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim lstTextAreas As jsTextArea() = js.Deserialize(Of jsTextArea())(textAreaJson)
Here's a function to Deserialize JSON of any type:
Public Function DeserializeJson(Of T)(json As String) As T
Return New JavaScriptSerializer().Deserialize(Of T)(json)
End Function

Dim and set the variable in 2 lines in vb.net

i have this line:
Dim strings_extreme = input.Split(","c).Distinct().OrderBy(Function(s) s)
i need to Dim it in one line, and set it a value on another line
how do i do that?
would it just be Dim strings_extreme() ??
and then strings_extreme = input.split.... ?
Even though VB.net allows you not to specify the type, it's always more safe to specify it explicitly. Hence:
Dim strings_extreme as string()
strings_extreme = input...
Just like this:
Dim strings_extreme
strings_extreme = input.Split(","c).Distinct().OrderBy(Function(s) s)
One note, though. I would turn on option strict. Its never a good idea to declare a variable without a type.
Dim strings_extreme As String()
Pretty close. Here it is:
Dim strings as string = "grape,apples,lime"
Dim strings_extreme
strings_extreme = Input.Split(strings,",").Distinct().OrderBy(Function(s) s)
for each e in strings_extreme
e.tostring 'do something with this
next