问题描述
我要寻找其转换一个单行列表< T>
到 [对象]
。这是单行,所以我的解决方案并不感兴趣,如的foreach
或为
...
任何考生?
提示:没有,无论是列表< T> .ToArray()
和列表< T> .ToArray<对象>()
不起作用。
编辑:为什么列表< T> .ToArray<对象>()
不起作用?因为它不能编译。
mylist.Cast<对象>()ToArray的()
这只会重复一次,顺便说一句,如果你想知道有关性能。上)。 :)
为什么呢?嗯,因为将使用延迟执行,直至该名单是由 ToArray的迭代实际上不会做任何事情()
。
编辑:或者,你可以使用LINQ做同样的事情在一个符合一次迭代:
VAR myObjectArray =(从myList中选择项目为对象的项目).ToArray();
首先是可能更容易理解和类型,但第二个更有趣,因为,嘿,这是LINQ!
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
...
Any takers?
Hint: No, both List<T>.ToArray()
and List<T>.ToArray<object>()
don't work.
Edit: 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). :)
Why? Well, because Cast<object>
will use deferred execution and won't actually do anything until the list is iterated by ToArray()
.
Edit: Alternatively, you could use LINQ to do the same thing in one line with one iteration:
var myObjectArray = (from item in myList select item as object).ToArray();
The first is probably easier to understand and type, but the second is much more fun, because, hey, it's LINQ!
这篇关于转换列表&LT; T&GT;反对[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!