Given an array of strings, say: Dim array1 As String() = {"1", "2", "3"} what is the best way to copy that array and perform an action on each element?
In other words, what is the best way to copy that array to come up with: array2 as integer() = {1, 2, 3}
For example, something similar to JavaScript's .Map function:
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
// Result: 2, 3, 4, 5
If it isn't possible in one line - as I suspect it isn't - what is your quickest alternative? Thanks!
If you don't want to use any LINQ extension methods, but you are okay with using lambda expressions, you can still do it in one line using Array.ConvertAll:
Dim input() As String = {"1", "2", "3"}
Dim output() As Integer = Array.ConvertAll(input, Function(x) Integer.Parse(x))
However, it does beg the question: why not just use LINQ, at that point, since it's effectively the same thing:
Dim input() As String = {"1", "2", "3"}
Dim output() As Integer = input.Select(Function(x) Integer.Parse(x)).ToArray()
The classic imperative way to do this in VB, without using LINQ or lambdas, would be a for-loop:
Dim input() As String = {"1", "2", "3"}
Dim output(LBound(input) To UBound(input)) As Integer
For i As Integer = LBound(input) To UBound(input)
output(i) = Integer.Parse(input(i))
Next
I would like to add that, similar to JavaScript, .NET's map equivalent Select also supports method groups as well as lambdas.
Here's an example using a lambda:
Dim output = input.Select(Function(x) SomeMethod(x)).ToArray()
Here's an example using a method group. Since parenthesis on method invocations are optional in VB.NET, the additional AddressOf keyword is required:
Dim output = input.Select(AddressOf SomeMethod).ToArray()
For completeness, here's an example using the LINQ query syntax, which is just syntactic sugar for the first example:
Dim output = (From x In input Select SomeMethod(x)).ToArray()
If you don't want to use LINQ here is the classic way, a loop:
Dim numbers = {4, 9, 16, 25}
For i As Int32 = 0 To numbers.Length - 1
numbers(i) = CInt(Math.Sqrt(numbers(i)))
Next
Related
I'm trying to write code to show data from two arrays via a MsgBox(). I have the code below, but of course it doesn't work:
Dim numbers() As Integer = {1, 4, 7}
Dim letters() As String = {"a", "b", "c"}
' Iterate through the list by using nested loops.
For Each number As Integer In numbers and For Each letter As String In letters
MsgBox(number.ToString & letter & " ")
Next
What do I need to do to get output that looks like this? :
1a
4b
7c
You need a For loop that uses an index rather than a For Each loop:
Dim numbers() As Integer = {1, 4, 7}
Dim letters() As String = {"a", "b", "c"}
For i As Integer = 0 To numbers.Length - 1
MsgBox(numbers(i) & letters(i))
Next
You can also use the Zip() linq operator:
For Each output As String In numbers.Zip(letters, Function(n, l) n & l)
MsgBox(output)
Next
You may benefit from something like a dictionary. Not sure what you're trying to accomplish combining 2 arrays arbitrarily but something like this may be better:
Dim Dict As New Dictionary(Of Integer, String) From {{1, "a"}, {4, "b"}, {7, "c"}}
For Each Item In Dict
MsgBox(Item.Key & Item.Value)
Next
That would allow you to lookup items based on the ID (integer) with Linq such as:
Dict.Where(Function(x) x.Key = 1).SingleOrDefault and grab the key/value pair.
So I'm trying to select a random element and then save said element, not quite knowing as to how I would go about doing this. The first thing that came to mind, although messy to write was:
Rnd(griddata(1), griddata(2), griddata(...))
I did receive an error however from this:
Overload resolution failed because no accessible 'Rnd' accepts this
number of arguments.
The plan is to store whatever random element it chooses as memory as well.
Any help would be greatly appreciated. Thanks!
Dim myArray() As Integer = {1, 10, 12, 11, 44, 23, 2, 1, 5, 6, 2, 7}
Dim rnd As New Random
Dim randomArrayElement = myArray(rnd.Next(0, myArray.Length - 1))
Or even you can try the same from a string also
Dim chars = "0123456789"
Dim random = New Random()
Dim result = New String(Enumerable.Repeat(chars, 1).[Select](Function(s) s(randomOtp.[Next](s.Length))).ToArray())
Dim rnd = new Random()
...
Dim randomIndex = rnd.Next(0, griddata.Length)
Dim randomValue = griddata(randomIndex)
This is assuming that your array is 0-based (as .NET arrays usually are).
whats the easiest way to convert an array of integers into string form? I'm trying to copy the whole array of integers into strings.
{1, 2, 3}
to
{"1", "2", "3"}
The easiest method would be to use the Select extension method which is provided by LINQ:
Dim intArray() As Integer = {1, 2, 3}
Dim strArray() As String = intArray.Select(Function(x) x.ToString()).ToArray()
If you don't want to, or cannot use LINQ, you can use the Array.ConvertAll method, which is almost as easy:
Dim strArray() As String = Array.ConvertAll(Of Integer, String)(intArray, Function(x) x.ToString())
EDIT
Based on your comments, below, it looks like you need to convert from an ArrayList of integers to an ArrayList of strings. In that case, you could do it like this:
Dim intArray As New ArrayList({1, 2, 3})
Dim strArray As New ArrayList(intArray.ToArray().Select(Function(x) x.ToString()).ToArray())
Although, at that point, it's starting to get a bit messier. It's probably easier to just do a standard loop, like this:
Dim myArray As New ArrayList({1, 2, 3})
For i As Integer = myArray.Count - 1 To 0 Step -1
myArray(i) = myArray(i).ToString()
Next
For what it's worth, though, unless you are still on a really old version of the .NET Framework, you really ought to be using the List(Of T) class rather than the ArrayList class, in most cases.
In VB.NET, I create my arrays like
Dim myArray = New ArrayList
But isn't there a way to create an array with elements without having to make a variable?
In Ruby, the long way was
array = Array.new
And the simple, non-variable way was just
[element,element,...]
Well, things you can do with primitive (and String) arrays:
Dim array As New String()
Dim array As New String() { "one", "two", "three" }
If (New String() { "one", "two", "three" }).Contains("one") Then
' Do something for "one"
End If
If you move to VB.NET 2010 you will get some extra array initialization features, but if you're using 2008 or below the shortest you can get your lists created might be something like this:
Dim list As New List(Of String)
list.AddRange(New String() { "one", "two", "three" })
And to touch on the point of declaring things without assigning them to a variable: .NET is strongly typed, so while you don't always have to declare a variable, your objects will always need to be of a single type (and one you need to specify through a New).
I'm not sure just how useful such a beast is since, without a name, you can't easily access the elements of it.
I know C has a feature that allows this with "one-shot" accesses like:
char hexchar = "0123456789abcdef"[nybble];
but, after that statement's finished the char array making up that string is no longer accessible.
If you want an array you can access continuously, I suspect it will need an identifying name. I might be wrong, I haven't used VB since VB6 but even if it's possible, it's a dubious language feature (IMO).
You can do a few things.
Public Sub Main()
Dim xs = New Integer() {1, 2, 3}
CType({1, 2, 3}, Integer()).CopyTo(...)
Dim s2 = Sum({1, 2, 3})
End Sub
Public Function Sum(ByVal array As Integer()) As Integer
Return array.Sum()
End Function
Is this the kind of thing you're after?
For Each foo As String In New String() {"one", "two", "three"} 'an array with no name - "On the first part of the journey..."
Debug.WriteLine(foo)
Next
I wrote this - very simple - function, and then wondered does VB have some pre-built functionality to do this, but couldn't find anything specific.
Private Shared Function MakeArray(Of T)(ByVal ParamArray args() As T) As T()
Return args
End Function
Not so much to be used like
Dim someNames() as string = MakeArray("Hans", "Luke", "Lia")
Because this can be done with
Dim someNames() as string = {"Hans", "Luke", "Lia"}
But more like
public sub PrintNames(names() as string)
// print each name
End Sub
PrintNames(MakeArray("Hans", "Luke", "Lia"))
Any ideas?
Any reason not to do:
Dim someNames() as string = New String(){"Han", "Luke", "Leia"}
The only difference is type inference, as far as I can tell.
I've just checked, and VB 9 has implicitly typed arrays too:
Dim someNames() as string = { "Han", "Luke", "Leia" }
(This wouldn't work in VB 8 as far as I know, but the explicit version would. The implicit version is necessary for anonymous types, which are also new to VB 9.)
Dim somenames() As String = {"hello", "world"}
The following codes will work in VB 10:
Dim someNames = {"Hans", "Luke", "Lia"}
http://msdn.microsoft.com/en-us/library/ee336123.aspx
PrintNames(New String(){"Hans", "Luke", "Lia"})
Microsoft recommends the following format
Dim mixedTypes As Object() = New Object() {item1, item2, itemn}
per http://msdn.microsoft.com/en-US/library/8k8021te(v=VS.80).aspx
Note, you don't have to specify the size of new Array, as that is inferred from the initialized count of args. If you do want to specify the length, you specify not the "length" but index number of last space in array. ie. New Object(2) {0, 1, 2} ' note 3 args.