User59
User59

Reputation: 517

Convert integer hashset to a integer array

So i have made a hashset with -you've guessed it- integers in it. Now i need to convert this into a array, so i can refer to each array 'cell' and use the value from the hashset in a process.

Currently i add to the hashset like so:

 While NumbersToRemember.Count < 1
            RandomNumber = Random.Next(2, 6)
            If NumbersToRemember.Add(RandomNumber) then ...

i have tried using NumbersToRemember.ToArray() but it hasnt been working as expected.

Any advice?

Note: See comment by JerryM for the solution.

Upvotes: 1

Views: 336

Answers (1)

There is not even a complete loop shown, so it is hard to tell what might be happening. it outputs only zeros in comments indicates something else might be wrong. Test:

Dim hs As New HashSet(Of Int32)
Dim temp As Int32

For n As Int32 = 1 To 10
    temp = rng.Next(2, 16)
    If hs.Contains(temp) = False Then
        hs.Add(temp)
    End If

Next

Dim nums = hs.ToArray
Console.WriteLine("Vals: {0}", String.Join(", ", hs.ToArray()))
Console.WriteLine("Nums: {0}", String.Join(", ", nums))

Output:

Vals: 2, 7, 14, 11, 12, 10
Nums: 2, 7, 14, 11, 12, 10

It is hard to tell what you are trying to do, but to get a small set of random values in a given range, this seems a bit simpler:

Dim count As Int32 = 6
Dim randvals = Enumerable.Range(2, 16).
                OrderBy(Function(x) Rnd.Next()).
                Take(count).ToArray()
Console.WriteLine("Rand Vals: {0}", String.Join(", ", randvals))

Rand Vals: 2, 13, 8, 6, 3, 12

Upvotes: 1

Related Questions