Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a quick way to convert a List<List<string>> to string[][]?

Tags:

arrays

c#

list

.ToArray doesn't do it

like image 590
KevinDeus Avatar asked Jul 01 '10 22:07

KevinDeus


People also ask

How do I convert a string to a list of one strings?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

Can we convert list of string to string in Java?

We use the toString() method of the list to convert the list into a string.

How do I convert a list of numbers to string?

You can convert an integer list to a string list by using the expression list(map(str, a)) combining the list() with the map() function. The latter converts each integer element to a string.


2 Answers

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();
like image 142
luke Avatar answered Oct 02 '22 14:10

luke


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();
like image 41
Jon Skeet Avatar answered Oct 02 '22 13:10

Jon Skeet