Question

my code is as follows:

 Dim rows As New List(Of List(Of Integer))
    For i = 0 To cells.Count - 1
        rows(cells(i).x).Add(i)
    Next

basically the purpose of it is to go through all the "cells" (a self-defined structure) and group them based on their x-values. my desired output is all cells with x-value "0" for example have their indexes stored together in rows(0). my problem is that I get (presumably) a null reference exception when I try to refer to a row by index because i have not yet declared it. however I am at a loss as to how I am supposed to build up multiple lists at the same time, when I don't know how many lists there are going to be beforehand. any help?

Was it helpful?

Solution

There are a couple of issues here. Firsly the Add method takes a List(Of Integer) but you are providing an Integer. I'm not sure what collection you wanted to use there but it needs to be something other than i.

Secondly when you say rows(cells(i).x) it's indexing into the created rows value but you haven't actually put anything into the list. You can only index into existing values which you haven't added yet.

Based on your comments I think the best data structure here is Dictionary(Of Integer, List(Of Integer)). This will allow you to map the x values to a collection of indexes that contain that value.

Dim map As New Dictionary(Of Integer, List(Of Integer))
For i = 0 To cells.Count -1 
  Dim x = cells(i).x
  Dim list As List(Of Integer)

  If Not map.TryGetValue(x, list) Then
    list = New List(Of Integer)
    map(x) = list
  End If 

  list.Add(i)
Next

I don't think a List(Of List(Of Integer)) is appropriate because it would require that the x values be contiguous and increasing to work properly. Maybe that's true here but I think it's unlikely

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top