Convert string array to int array - vb.net

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

Related

How to convert an array from string to integer

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)

How i can get selected parts from string?

How i get string like
'EJ0004','EK0001','EA0001'
from string like
{Emaster.Emp_Code}='EJ0004' OR {Emaster.Emp_Code}='EK0001' OR {Emaster.Emp_Code}='EA0001'
in VB.NET?
You can use a regular expression.
Example:
Sub Main
Dim s = "{Emaster.Emp_Code}='EJ0004' OR {Emaster.Emp_Code}='EK0001' OR {Emaster.Emp_Code}='EA0001'"
Dim pattern = "('\w*')"
Dim matches = Regex.Matches(s, pattern)
Dim values = matches.OfType(Of Match).Select(Function(m) m.Value)
For Each v in values
Console.WriteLine(v)
Next
Console.WriteLine(String.Join(",", values))
End Sub
Output:
'EJ0004'
'EK0001'
'EA0001'
'EJ0004','EK0001','EA0001'
there are many ways you could do this, here i offer one simple way:
dim yourString as string = 'This is the variable which holds your initial string
dim newString as string = yourString.replace("{Emaster.Emp_Code}=", "").replace(" OR ",",")
Now newString will hold 'EA0001' Or whatever.
If you want it without the '' then do
dim newString as string = yourString.replace("{Emaster.Emp_Code}=", "").replace("'","").replace(" OR ",",")

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"} )

setting strings_array(0) = "" problem

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

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"))