Vibi Chrisbud
Vibi Chrisbud

Reputation: 57

What is the most elegant way to create a list of boolean of 100 elements initialized at false

Obviously I can do

    Dim primeornot = New List(Of Boolean)
    For i = 1 To 100
        primeornot.Add(False)
    Next

Which is actually short enough and probably don't take much longer than proper version.

Is there a more proper way to do this?

Upvotes: 0

Views: 166

Answers (4)

Jimi
Jimi

Reputation: 32278

You have a lot ways to create a collection, as a List(Of T) or anything else.
Depending on the use case:

Hard-code the size, when you know in advance how many items the collection contains:

Dim bList = New Boolean(99) {}.ToList()

Based on parameters, using the List(Of T) constructor:

Dim items = 100
Dim bList = New List(Of Boolean)(New Boolean(items - 1) {})

Dim times = 100 : Dim value = False
Dim bList = New List(Of Boolean)(Enumerable.Repeat(value, times))

When you have two values that define a range:

Dim range As (iFrom As Integer, iTo As Integer, bValue As Boolean) = (50, 100, False)
Dim bList = Enumerable.Range(range.iFrom, range.iTo).Select(Function(b) range.bValue).ToList()

When you pre-build a Func(Of T, [NumberOfItems], ReturnType(Of T)):

Dim myFunc = New Func(Of Boolean, Integer, IEnumerable(Of Boolean))
   (Function(b, i) Enumerable.Repeat(b, i))

' [...]
Dim bList = New List(Of Boolean)(myFunc(False, 100))

A generic method that returns an IEnumerable(OF T):

Dim boolList = GetCollection(100, False).ToList()
Dim decimalList = GetCollection(100, 100D).ToList()

' [...]

Public Function GetCollection(Of T As {Structure})
    (howMany As Integer, baseValue As T) As IEnumerable(Of T)
    Return Enumerable.Repeat(baseValue, howMany)
End Function

Upvotes: 2

Vibi Chrisbud
Vibi Chrisbud

Reputation: 57

I would say this look elegant

    Dim trueifnotprime = New List(Of Boolean)(100)

All the boolean element is automatically set to false isn't it?

Upvotes: 0

Sideways
Sideways

Reputation: 286

You can also use System.Collectios.BitArray instead:

Dim bitArray As New System.Collections.BitArray(100)

All 100 values will be initialized to false by default.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460228

You can use LINQ if you want a shorter version:

Dim primeornot = Enumerable.Repeat(False, 100).ToList()

Upvotes: 2

Related Questions