How to convert an array from string to integer - vb.net

I have an array "string()" with 3 element (2,5,6)
How do I convert all of element from string to int?
I tried CInt and Array.ConvertAll but they didn't work.
Please show me the way to do that. Thank you.

You have not said what type of problem you are having using Array.ConvertAll or shown your implementation of it, but this works for me.
Module Module1
Sub Main()
Dim mystringArray As String() = New String() {"2", "5", "6"}
Dim myintArray As Integer()
myintArray = Array.ConvertAll(mystringArray, New Converter(Of String, Integer)(AddressOf StringToInteger))
End Sub
Function StringToInteger(st As String) As Integer
Return CInt(st)
End Function
End Module

You can use the List(Of T).ConvertAll
Dim stringList = {'2','5','6'}.ToList
Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str))

Dim stringList() As String = {"2", "5", "6"}' string array
Dim intList() As Integer = {0, 0, 0, 0, 0}'integer array initialized with 0
For i As Integer = 0 To stringList.Length - 1
intList(i) = CInt(stringList(i))
Next
'Display the list
For i = 0 To intList.Length - 1
MsgBox(intList(i))
Next

This works like a charm:
Dim strArr As New List(Of String)(New String() {"2", "5", "6"})
Dim intList As List(Of Integer) = strArr.ConvertAll(New Converter(Of String, Integer)(AddressOf Integer.Parse))
No need to define a custom parser. Have look at its documentation as well:

My VB is rusty but I would do something like this:
intList = (From s in stringList Select CInt(s)).ToArray()

Just use a lambda,
Dim intList As IList(Of Integer)
Dim list1 = "1,2,3".Split(",")
intList = list1.ConvertAll(Function(s) Integer.Parse(s))
or
Dim intList As IList(Of Integer)
Dim list1 = "1,2,3".Split(",")
intList = list1.ConvertAll(AddressOf Integer.Parse)

Related

Convert a List to a Dictionary with a unique numbered key

How can this code be accomplished using ToDictionary() instead of a For Each
Dim stringDict As Dictionary(Of String, String) = new Dictionary(Of Integer, String)
Dim stringList As List(Of String) = {"alpha", "beta", "gamma", "delta"}
For Each stringItem As String In stringList
stringDict.Add($"Entry{stringDict.Count+1}",stringItem)
Next
This is what I am trying to do:
Dim stringDict As Dictionary(Of String, String) = stringList.ToDictionary(Function(a) $"Entry{?}", Function(b) b)
I was hoping there might be a variable with the current row or index, or an incrementor
You can use the overload of Select that gives you the index:
Dim stringDict As Dictionary(Of String, String) = stringList.
Select(Function(s, index) (Key:=$"Entry{index + 1}", Value:=s)).
ToDictionary(Function(kv) kv.Key, Function(kv) kv.Value)
However, i find your loop more readable. You should also set Option Strict to On, following should give you a compiler error:
Dim stringDict As Dictionary(Of String, String) = new Dictionary(Of Integer, String)
You can use Enumerable.Range (documentation) to create a range of numbers from 1 to the Count of your List and then Enumerable.ToDictionary (documentation) to convert that range to a Dictionary.
Example:
Dim stringList As New List(Of String) From {"alpha", "beta", "gamma", "delta"}
Dim stringDict = Enumerable.Range(1, stringList.Count).ToDictionary(Function(i) $"Entry{i}", Function(i) stringList.Item(i - 1))
Fiddle: https://dotnetfiddle.net/4xHp9g

Length of 2D String list does not return the right value

I have a problem when I use .count in my 2D String list. This is the code:
If File.Exists(fullPath) = True Then
Dim readText() As String = File.ReadAllLines(fullPath)
Dim s As String
accountCounter = 0
For Each s In readText
accountList.Add(New List(Of String))
accountList.Add(New List(Of String))
accountList.Add(New List(Of String))
accountList(accountCounter).Add(s.Split(",")(0))
accountList(accountCounter).Add(s.Split(",")(1))
accountList(accountCounter).Add(s.Split(",")(2))
accountCounter += 1
Next
print_logs(accountList.count)
End If
The result is this:
{{name,email,password},{name2,email2,password2},{name3,email3,password3},{name4,email4,password4}}
beacuse in the file there are the following lines:
name,email,password
name2,email2,password2
name3,email3,password3
name4,email4,password4
But data is not the problem, the real problem is the Count method, it returns (12). I think that it returns 4 * 3 result, because if I add this in the code:
print_logs(accountList(0).Count)
it correctly returns 3.
So, how can I just return 4?
In this code you create three new rows everytime you do an iteration... If there are four lines in your text files then you will create twelve...
Do this instead :
If File.Exists(fullPath) = True Then
Dim readText() As String = File.ReadAllLines(fullPath)
Dim s As String
accountCounter = 0
For Each s In readText
accountList.Add(New List(Of String))
accountList(accountCounter).Add(s.Split(",")(0))
accountList(accountCounter).Add(s.Split(",")(1))
accountList(accountCounter).Add(s.Split(",")(2))
accountCounter += 1
Next
print_logs(accountList.count)
End If
And if you want to make it even better :
If File.Exists(fullPath) = True Then
Dim readText() As String = File.ReadAllLines(fullPath)
For Each s As String In readText
Dim newList = New List(Of String)
newList.Add(s.Split(",")(0))
newList.Add(s.Split(",")(1))
newList.Add(s.Split(",")(2))
accountList.Add(newList)
Next
print_logs(accountList.count)
End If

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

How can I search an array in VB.NET?

I want to be able to effectively search an array for the contents of a string.
Example:
dim arr() as string={"ravi","Kumar","Ravi","Ramesh"}
I pass the value is "ra" and I want it to return the index of 2 and 3.
How can I do this in VB.NET?
It's not exactly clear how you want to search the array. Here are some alternatives:
Find all items containing the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))
Find all items starting with the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))
Find all items containing any case version of "ra" (returns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))
Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
-
If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.
Example:
Function ContainsRa(s As String) As Boolean
Return s.Contains("Ra")
End Function
Usage:
Dim result As String() = Array.FindAll(arr, ContainsRa)
Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:
Public Class ArrayComparer
Private _compareTo As String
Public Sub New(compareTo As String)
_compareTo = compareTo
End Sub
Function Contains(s As String) As Boolean
Return s.Contains(_compareTo)
End Function
Function StartsWith(s As String) As Boolean
Return s.StartsWith(_compareTo)
End Function
End Class
Usage:
Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))
If you want an efficient search that is often repeated, first sort the array (Array.Sort) and then use Array.BinarySearch.
In case you were looking for an older version of .NET then use:
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result As New List(Of Integer)
For i As Integer = 0 To arr.Length
If arr(i).Contains("ra") Then result.Add(i)
Next
End Sub
End Module
check this..
string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
Array.IndexOf(strArray, "C"); // not found, returns -1
Array.IndexOf(strArray, "CDE"); // found, returns index
compare properties in the array if one matches the input then set something to the value of the loops current position, which is also the index of the current looked up item.
simple eg.
dim x,y,z as integer
dim aNames, aIndexes as array
dim sFind as string
for x = 1 to length(aNames)
if aNames(x) = sFind then y = x
y is then the index of the item in the array, then loop could be used to store these in an array also so instead of the above you would have:
z = 1
for x = 1 to length(aNames)
if aNames(x) = sFind then
aIndexes(z) = x
z = z + 1
endif
VB
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()
C#
string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();
-----Detailed------
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim searchStr = "ra"
'Not case sensitive - checks if item starts with searchStr
Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Case sensitive - checks if item starts with searchStr
Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Not case sensitive - checks if item contains searchStr
Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
Stop
End Sub
End Module
Never use .ToLower and .ToUpper.
I just had problems in Turkey where there are 4 "i" letters. When using ToUpper I got the wrong "Ì" one and it fails.
Use invariant string comparisons:
Const LNK as String = "LINK"
Dim myString = "Link"
Bad:
If myString.ToUpper = LNK Then...
Good and works in the entire world:
If String.Equals(myString, LNK , StringComparison.InvariantCultureIgnoreCase) Then...
This would do the trick, returning the values at indeces 0, 2 and 3.
Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))