.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
2010-07-01 22:42:12
very informative.
KevinDeus
2010-07-01 22:56:54
well i may not have gotten the green check, but at least i beat jon skeet!
luke
2010-07-01 23:03:34
+2
A:
List<List<string>> myStrings;
myStrings.Select(l => l.ToArray()).ToArray();
(LINQ rocks)
Matt Greer
2010-07-01 22:43:12
+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
2010-07-01 22:45:42
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
2010-07-01 22:55:52
@Jon, yeah.. you heard what I meant.. Is there a quick way to convert it back?
KevinDeus
2010-07-02 16:42:37
@KevinDeus: I edited it into the answer when I asked the question, just in case I was right :)
Jon Skeet
2010-07-02 16:51:32
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
2010-10-21 15:53:44