tags:

views:

146

answers:

3

.ToArray doesn't do it

+12  A: 

Linq is the way to go on this one.

List<List<String>> list = ....;
string[][] array = list.Select(l => l.ToArray()).ToArray();

to break it down a little more the types work out like this:

List<List<String>> list = ....;
IEnumerable<String[]> temp = list.Select(l => l.ToArray());
String[][] array = temp.ToArray();
luke
very informative.
KevinDeus
well i may not have gotten the green check, but at least i beat jon skeet!
luke
+2  A: 
List<List<string>> myStrings;

myStrings.Select(l => l.ToArray()).ToArray();

(LINQ rocks)

Matt Greer
+9  A: 

One quick variation on the existing answers, which uses a method group conversion instead of a lambda expression:

string[][] array = lists.Select(Enumerable.ToArray).ToArray();

In theory it'll be every so slightly faster, as there's one less layer of abstraction in the delegate passed to Select.

Remember kids: when you see a lambda expression of this form:

foo => foo.SomeMethod()

consider using a method group conversion. Often it won't be any nicer, but sometimes it will :)

Getting back to a List<List<string>> is easy too:

List<List<string>> lists = array.Select(Enumerable.ToList).ToList();
Jon Skeet
just for giggles, how about converting back to string[][]?
KevinDeus
Up to now I did not realize the fact that using a method group saves one level of indirection - I never really thought about it and always interpreted it as a kind of syntactic sugar. +1 for this insight.
Daniel Brückner
awarded for efficiency as well
KevinDeus
@KevinDeus: Do you mean back to a `List<List<string>>`?
Jon Skeet
@Jon, yeah.. you heard what I meant.. Is there a quick way to convert it back?
KevinDeus
@KevinDeus: I edited it into the answer when I asked the question, just in case I was right :)
Jon Skeet
Just wanted to add that if you want to use a method-group conversion for `Select` in C# 3.0, the generic type-arguments need to be specified explicitly since return type inference does not work on method groups in C# 3. http://blogs.msdn.com/b/ericlippert/archive/2007/11/05/c-3-0-return-type-inference-does-not-work-on-member-groups.aspx
Ani