将List<T>转换为object[]

29

我正在寻找一行代码,可以将List<T>转换为object[]。这是一行代码,所以我不希望看到使用foreachfor的解决方案...

有人愿意尝试吗?

提示:不,List<T>.ToArray()List<T>.ToArray<object>()都不可行。

编辑:为什么List<T>.ToArray<object>()不可行?因为它无法编译。


为什么 List<T>.ToArray() 和 List<T>.ToArray<object>() 不起作用? - Jared Bienz - MSFT
@Jared: 因为 ToArray<object> 无法编译 - 类型必须与列表的基础类型匹配。 - Randolpho
3
@JoshJordan:这个问题并没有错。他只是对3.5版本中的某些新扩展方法不了解而已。他尝试了两次但失败了。 - Randolpho
1
我不明白为什么有人不喜欢使用循环。事实上,任何一行代码的解决方案都可能在内部执行循环。实际上,如果扩展方法不存在,你也可以自己编写...使用循环。 - Michael Meadows
@Michael:你说得没错,内部循环绝对是必须的;无法避免。但它可以很容易地在一行中完成;有关详细信息,请参见我的答案。 - Randolpho
我不知道谁给你的问题点了踩,但完全没有必要;这是一个合理的问题。 - Randolpho
8个回答

74
mylist.Cast<object>().ToArray()

顺便说一下,那只会迭代一次,如果你关心性能的话。 O(n).

为什么呢?因为 Cast<object> 使用延迟执行,直到通过 ToArray() 进行迭代,它才会真正做任何事情。


3
没有在强制转换的通用参数上看到,所以我发布了另一个答案。这是正确的答案。+1 - Stefan Steinegger
3
两者都是LINQ。第二个是一个LINQ查询。 - Samuel
2
@Randolpho:你的回答在将近7年后帮了我大忙。点赞 :) - ismail baig

10
List<T>.Select(x => x as object).ToArray();

应该返回一个 object[]


1
这应该是被接受的答案!@Randolpho - Mike
2
@Mike 我不同意。是的,它们在功能上是等效的,但 Cast 是更好的选择,因为它不需要或创建一个 lambda。Lambda 可能很便宜,但它们并不是免费的。 - Randolpho

3

如果您没有Linq (.Net 3.0),则可以使用List中的ConvertAll()ToArray()方法:

List<T> list = new List<T>();

object[] objects = list.ConvertAll<object>(item => (object)item).ToArray();

2
theList.Cast<object>().ToArray()

或者
new List<object>(theList).ToArray()

2
你的第一个选项更好。你的第二个选项将会两次迭代列表。Cast<object> 不会实际迭代列表。 - Randolpho
@Randolpho,如果我说错了,请纠正我,但要创建数组,ToArray必须遍历列表。强制转换被推迟到此发生之前,但由于它发生在同一行上,因此实际上是迭代整个列表。然而,选项2看起来似乎会迭代两次。 - Michael Meadows
@Samuel,我同意选项二会迭代两次的评估,但是质疑 Cast<object> 不会迭代的说法。虽然这个陈述本身是正确的,但它可能会让人们认为没有迭代。我不认为这是 @Randolpho 试图表达的,但它似乎只是这样。我只是在寻求澄清。 - Michael Meadows
@both:对于之前的误解,我深感抱歉。明确一下:第一个选项只会迭代一次,因为ToArray()方法的调用将枚举迭代一次,但Cast<object>()方法不会迭代,因为它使用延迟执行。请参见我的答案中的链接以了解其工作原理。第二个选项将迭代两次,因为List构造函数在构建期间将进行迭代,并且ToArray()调用将迭代第二次以构建数组。 - Randolpho
嗯,我从未尝试过提出最优化的解决方案,而是最易读或直观的方案。人们理解和记住的事情也很重要。 - Stefan Steinegger
显示剩余4条评论

2
(object[])List<T>.ToArray();

您不需要转换类型,引用类型本身就是对象。 - stevehipwell
@Stevo3000 他确实需要进行强制类型转换,因为这是原问题的要求。需要将其转换为对象数组。 - Randolpho
@Randolpho - 不对,所有引用类型都是对象。仅仅因为问题要求进行强制转换并不意味着它是必需的。任何引用类型都可以被存储为对象。 - stevehipwell

1
如果您不介意编写一个非常短小且可重用的函数,ConvertAll扩展方法可能会有所帮助:

http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx

编辑:

这也可以工作

List<int> intList = new List<int>() { 1, 3, 4 };
object[] objectList = intList.ConvertAll(item => (object)item).ToArray();

为什么?如果他只需要 object[],那么 .Cast<object>() 就是完美的。 - Samuel

0
在.NET 2.0(VS 2008)的C#中,以下内容编译通过,并且不使用LINQ(就我所知)用于引用类型。
 object[] oArray;
 List<MyObject> oList = new List<MyObject>();
 oArray = oList.ToArray();

这不需要强制转换,因为所有引用类型都以 object 作为它们的基类。


它在我的机器上无法编译:VS 2008,.net 3.5。 - Graviton
@Ngu Soon Hui - 你确定你使用的是引用类型吗?在我的VS 2008机器上,它以.NET 3.5编译完美。 - stevehipwell

-1

我建议创建一个ListCastAdapter,

假设你想将List转换为List

创建一个IList的实现,该实现从List返回项目

我很可能称之为class ListCastAdapter

祝你有美好的一天

实现(未经测试):

注意:建议将列表设置为只读, 因为现在用户可以插入原始列表中层次结构较高的对象。

注意:CopyTo()方法未实现,你可以为数组创建相同的思路。

using System.Collections;
using System.Collections.Generic;

namespace UDF.MyDataLayer
{
    internal class ListCastAdapter<S,T> : IList<T> where T : class where S : class
    {
        private List<S> adaptee;

        public ListCastAdapter(List<S> adaptee )
        {
            this.adaptee = adaptee;
        }

        #region Implementation of IEnumerable

        public class EnumeratorCastAdapter : IEnumerator<T>
        {
            private IEnumerator<S> adaptee;

            public EnumeratorCastAdapter(IEnumerator<S> adaptee)
            {
                this.adaptee = adaptee;
            }

            #region Implementation of IDisposable

            /// <summary>
            /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
            /// </summary>
            /// <filterpriority>2</filterpriority>
            public void Dispose()
            {
                adaptee.Dispose();
            }

            #endregion

            #region Implementation of IEnumerator
            /// <summary>
            /// Advances the enumerator to the next element of the collection.
            /// </summary>
            /// <returns>
            /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
            /// </returns>
            /// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
            public bool MoveNext()
            {
                return adaptee.MoveNext();
            }

            /// <summary>
            /// Sets the enumerator to its initial position, which is before the first element in the collection.
            /// </summary>
            /// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
            public void Reset()
            {
                adaptee.Reset();
            }

            /// <summary>
            /// Gets the element in the collection at the current position of the enumerator.
            /// </summary>
            /// <returns>
            /// The element in the collection at the current position of the enumerator.
            /// </returns>
            public T Current
            {
                get
                {
                    // needs to check if it is an Object or Value Type
                    return adaptee.Current as T;
                }
            }

            /// <summary>
            /// Gets the current element in the collection.
            /// </summary>
            /// <returns>
            /// The current element in the collection.
            /// </returns>
            /// <exception cref="T:System.InvalidOperationException">The enumerator is positioned before the first element of the collection or after the last element.</exception><filterpriority>2</filterpriority>
            object IEnumerator.Current
            {
                get { return Current; }
            }
            #endregion
        }
        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        public IEnumerator<T> GetEnumerator()
        {
            return new EnumeratorCastAdapter(adaptee.GetEnumerator());
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return adaptee.GetEnumerator();
        }
        #endregion

        #region Implementation of ICollection<T>
        /// <summary>
        /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
        public void Add(T item)
        {
            adaptee.Add(item as S);
        }

        /// <summary>
        /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
        public void Clear()
        {
            adaptee.Clear();
        }

        /// <summary>
        /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
        /// </summary>
        /// <returns>
        /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
        /// </returns>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        public bool Contains(T item)
        {
            return adaptee.Contains(item as S);
        }

        /// <summary>
        /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
        /// </summary>
        /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
        public void CopyTo(T[] array, int arrayIndex)
        {
            throw new System.NotImplementedException("Not Needed by Me, implement ArrayCastAdapter if needed");
        }

        /// <summary>
        /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <returns>
        /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </returns>
        /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
        public bool Remove(T item)
        {
            adaptee.Remove(item as S);
        }

        /// <summary>
        /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </summary>
        /// <returns>
        /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
        /// </returns>
        public int Count
        {
            get { return adaptee.Count; }
        }

        /// <summary>
        /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </summary>
        /// <returns>
        /// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
        /// </returns>
        public bool IsReadOnly
        {
            get 
            {
                return true;  // change, to live on the edge
            }
        }
        #endregion

        #region Implementation of IList<T>
        /// <summary>
        /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
        /// </summary>
        /// <returns>
        /// The index of <paramref name="item"/> if found in the list; otherwise, -1.
        /// </returns>
        /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
        public int IndexOf(T item)
        {
            return adaptee.IndexOf(item as S);
        }

        /// <summary>
        /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param><param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
        public void Insert(int index, T item)
        {
            adaptee.Insert(index, item as S);
        }

        /// <summary>
        /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
        /// </summary>
        /// <param name="index">The zero-based index of the item to remove.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
        public void RemoveAt(int index)
        {
            adaptee.RemoveAt(index);
        }

        /// <summary>
        /// Gets or sets the element at the specified index.
        /// </summary>
        /// <returns>
        /// The element at the specified index.
        /// </returns>
        /// <param name="index">The zero-based index of the element to get or set.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
        public T this[int index]
        {
            get { return adaptee[index] as T; }
            set { adaptee[index] = value as S; }
        }
        #endregion
    }
}

2
你这里的一行代码写得很好啊... 你能解释一下这种写法为什么比那个已被接受的答案(已经超过两年了)更好吗? - jv42
Linq语句将迭代所有变量并返回一个转换后的数组...但它仍然是O(n)...如果你只需要几个成员,这种方法只会在你需要它们的时候执行。假设你有100000条记录,并且你需要将列表转换,同时你知道列表只会请求少数记录... 为什么要使用O(n),如果可以使用O(a):a<<n = O(1)。 - Tomer W
那么,您能解释一下您的帖子如何回答问题,即如何将List<>转换为Array,而不是从List中获取几个项吗?也许一个使用示例会更清楚? - jv42
尽管听起来有些尴尬,但是下面的帖子在大多数情况下是最好的选择。对于值类型的情况,可以使用这个方法。顺便说一句,@jv42,我们的目标不是特别需要一个object[]对象,而是需要一个类型为object的数组,List<object>正好提供了这个功能。我的建议是对这样的数组进行“惰性初始化”。 - Tomer W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接