开发者

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

开发者 https://www.devze.com 2023-01-05 23:07 出处:网络
.ToArray doesn\'开发者_如何转开发t do itLinq is the way to go on this one. List<List<String>> list = ....;

.ToArray doesn'开发者_如何转开发t do it


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();


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();


List<List<string>> myStrings;

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

(LINQ rocks)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号