转换列表<T>反对[] [英] Convert List<T> to object[]
问题描述
我正在寻找一种将 List
转换为 object[]
的单行代码.这是一个班轮,所以我对诸如 foreach
或 for
...
I am looking for a one liner that transforms List<T>
into object[]
. It's one liner, so I am not interested in solutions such as foreach
, or for
...
有人接受吗?
提示:不,List
和 List
都不起作用.
Hint: No, both List<T>.ToArray()
and List<T>.ToArray<object>()
don't work.
为什么 List
不起作用?因为它无法编译.
Why List<T>.ToArray<object>()
doesn't work? Because it can't compile.
推荐答案
mylist.Cast<object>().ToArray()
顺便说一下,这只会迭代一次,以防您对性能感到疑惑.在).:)
That will only iterate once, by the way, in case you were wondering about the performance. O(n). :)
为什么?好吧,因为 Cast
使用延迟执行并且在 ToArray()
迭代列表之前实际上不会做任何事情.
Why? Well, because Cast<object>
will use deferred execution and won't actually do anything until the list is iterated by ToArray()
.
这篇关于转换列表<T>反对[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!