5

When creating webservices, in c#, I have found it very useful to pass back jagged arrays, i.e. string[][]

I also found a neat trick to build these in a simple way in my code, which was to create a List and convert it by doing a ToArray() call.

e.g.

public string[][] myws() {
    List<string[]> output = new List<string[]>();
    return output.ToArray();
}

I would like to be able to employ a similar solution, but I can't think how to do something similar with a 3 level jagged array or string[][][], without resorting to loops and such.

Regards Martin

1 Answer 1

6

You can get there by doing a Select() which converts each inner List<string> to an array using ToArray(), and then converting those results using ToArray():

        var x = new List<List<string[]>>();

        string[][][] y = x.Select(a => a.ToArray()).ToArray();

And so on for as many levels deep as you'd want to go.

Sign up to request clarification or add additional context in comments.

5 Comments

to be clear this isn't avoiding "loops and such", it's just burying the implementation of those loops inside of LINQ. it's the right answer though.
@RobertLevy: True, it only avoids loops in the sense of having a cleaner appearance, internally, yes it still loops -- unfortunately any conversion from a list to an array at some point performs loops either explicitly or implicitly...
@RobertLevy: Actually, List<T>.ToArray() just does an Array.Copy() since the underlying storage for a List<T> is already an Array.
@DStanley: Good to know, I forgot List<T> already had a ToArray() implementation...
@DStanley And that will, at some level, still be performing a loop. It might be a more efficient loop if it's at a lower level, but at some point each bit of data in the list is being copied to a new location. The point here is mostly that the operation is, at best, O(sizeOfDimention^numberOfDimensions). It's not O(1) the way some people think that it might be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.