I know that I'm able to use LINQ to initialize a 1D array by doing this:
But is there a way that I could do the same thing for a 2D array too?Code:Dim foo() As Boolean = Enumerable.Range(0, 9).ToList().ConvertAll(Function(i) True).ToArray()
Printable View
I know that I'm able to use LINQ to initialize a 1D array by doing this:
But is there a way that I could do the same thing for a 2D array too?Code:Dim foo() As Boolean = Enumerable.Range(0, 9).ToList().ConvertAll(Function(i) True).ToArray()
1D:2D:Code:Dim foo() As Boolean = Enumerable.Repeat(True, 9).ToArray
miiiight be a bit of a cheat. Check the docs for Buffer.BlockCopy and see what you think. :)Code:Dim bools(3, 4) As Boolean
Buffer.BlockCopy(Enumerable.Repeat(True, bools.Length).ToArray, 0, bools, 0, bools.Length)
' proof is in the pudding:
Dim sb As New StringBuilder
For row As Integer = 0 To 3
For col As Integer = 0 To 4
sb.Append(bools(row, col)).Append(" ")
Next
sb.Append(vbCrLf)
Next
MsgBox(sb.ToString)
I like your 1D example much better than mine, and the 2D.... wow I would've never thought of that!
Is LINQ the best approach here? Best as in clearest, easiest to maintain, and fastest? Just wondering.
It's a cool trick, but I think I'd use Enumerable.Repeat().ToArray() for 1D and good old fashioned loops for 2D. It certainly wins code golf, but might not pass a code review.