Reputation: 561
I'm a beginner.my question is, I have an observablecollection(of string)
How can I add those collection's each elements as an array of string elements Using for loop?
Dim obsv as new observablecollection(of string) // has some collection of string
For each str in obsv
// How can I add that str into string Array
Next
Upvotes: 0
Views: 1517
Reputation: 4954
You can use LINQ .ToArray()
method. Or use the Item[Int32]
property.
Dim s As ObservableCollection(Of String)
' Whatever code to fill that collection.
' First solution:
Dim arr1 = s.ToArray() ' This needs the System.Linq namespace to be imported.
' Second solution:
Dim arr2(s.Count - 1) As String
For i As Integer = 0 To s.Count - 1
arr2(i) = s.Item(i)
Next
And here is a complete working code snippet:
Imports System
Imports System.Collections.ObjectModel
Imports System.Linq
Public Module Module1
Public Sub Main()
Dim s As New ObservableCollection(Of String)()
s.Add("Hello")
s.Add("World")
' Whatever code to fill that collection.
' First solution:
Dim arr1 = s.ToArray() ' This needs the System.Linq namespace to be imported.
Console.WriteLine("First array:")
Console.WriteLine(String.Join(", ", arr1))
Console.WriteLine()
' Second solution:
Dim arr2(s.Count - 1) As String
For i As Integer = 0 To s.Count - 1
arr2(i) = s.Item(i)
Next
Console.WriteLine("Second array:")
Console.WriteLine(String.Join(", ", arr2))
End Sub
End Module
Output is:
First array:
Hello, World
Second array:
Hello, World
Or if you want to use For Each loop, you can do it like that:
Dim arr2(s.Count - 1) As String
Dim i As Integer = 0
For Each str In s
arr2(i) = str
i += 1
Next
Upvotes: 1