C# jagged array to list of lists

Viewed 441

given a jagged array:

int[][] edges = new int[][] 
            {
                new int[] {0,1},
                new int[] {0,2},
                new int[] {0,3},
                new int[] {1,4},
            };

is there a more elegant way to do this:

var adjlist = new List<List<int>>();
            for(int i=0; i<n; i++)
            {
                adjlist.Add(new List<int>());
            }
            
            foreach(var arr in edges)
            {
                int src = arr[0];
                int dst = arr[1];

                adjlist[src].Add(dst);
                adjlist[dst].Add(src);
            }

something that improves on the time complexity for this would be ideal.

Thank you.

1 Answers

My assumption is the code in your example is not working as you intended (I may be wrong). However converting a jagged array to a list of lists should be as simple as the following. I doubt you will get much more efficient than this, though you could benchmark.

The following is O(n), meaning something somewhere needs to iterate over each element. That's to say, the memory can't be magicked. On saying that, ToList will call the List constructor with the collection and use the instance member CopyTo which in-turn uses Array.Copy and as such is extremely optimized for the data type and platform.

var results = edges.Select(x => x.ToList()).ToList();
Related