Results 1 to 5 of 5

Thread: Use LINQ to Initialize 2d Array

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,397

    Use LINQ to Initialize 2d Array

    I know that I'm able to use LINQ to initialize a 1D array by doing this:
    Code:
    Dim foo() As Boolean = Enumerable.Range(0, 9).ToList().ConvertAll(Function(i) True).ToArray()
    But is there a way that I could do the same thing for a 2D array too?
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  2. #2
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,335

    Re: Use LINQ to Initialize 2d Array

    1D:
    Code:
    Dim foo() As Boolean = Enumerable.Repeat(True, 9).ToArray
    2D:
    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)
    miiiight be a bit of a cheat. Check the docs for Buffer.BlockCopy and see what you think.

  3. #3

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,397

    Re: Use LINQ to Initialize 2d Array

    I like your 1D example much better than mine, and the 2D.... wow I would've never thought of that!
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  4. #4
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Use LINQ to Initialize 2d Array

    Is LINQ the best approach here? Best as in clearest, easiest to maintain, and fastest? Just wondering.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  5. #5
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Use LINQ to Initialize 2d Array

    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.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width