Convertir la liste en object

Je recherche une ligne qui transforme la List en object[] . C’est une ligne, alors je ne suis pas intéressé par des solutions telles que foreach , ou for

N’importe quels preneurs?

Astuce: Non, List.ToArray() et List.ToArray() ne fonctionnent pas.

Édition: Pourquoi la List.ToArray() ne fonctionne pas? Parce qu’il ne peut pas comstackr.

 mylist.Cast().ToArray() 

Soit dit en passant, cela ne se répète qu’une fois, au cas où vous vous interrogeriez sur la performance. Sur). 🙂

Pourquoi? Eh bien, parce que Cast utilisera l’exécution différée et ne fera rien tant que la liste ne sera pas itérée par ToArray() .

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

Devrait renvoyer un object[] .

Si vous n’avez pas Linq (.Net 3.0), vous pouvez utiliser les méthodes ConvertAll () et ToArray () dans List:

 List list = new List(); object[] objects = list.ConvertAll(item => (object)item).ToArray(); 
 theList.Cast().ToArray() 

ou

 new List(theList).ToArray() 

Et pour une solution pre-LINQ (qui ne fonctionne que pour les types de référence).

 (object[])List.ToArray(); 

Si cela ne vous dérange pas d’écrire une fonction très courte et réutilisable, la méthode d’extension ConvertAll peut vous aider:

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

MODIFIER:

Cela fonctionnerait aussi

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

En C # sur .NET 2.0 (VS 2008), les éléments suivants sont compilés et n’utilisent pas LINQ (autant que je sache) pour les types de référence.

  object[] oArray; List oList = new List(); oArray = oList.ToArray(); 

Cela ne nécessite pas de transtypage car tous les types de référence ont un object comme base.

Je suggère de créer un ListCastAdapter,

Disons que vous voulez convertir liste en liste

Créer une implémentation d’une implémentation d’IList qui renvoie des éléments d’une liste

le plus probable, je l’appelle la classe ListCastAdapter

Passez une bonne journée

mise en œuvre (non testé):

Remarque : Il est recommandé de créer la liste en lecture seule. En fait, l’utilisateur peut désormais insérer des objects se trouvant dans la hiérarchie supérieure dans la liste d’origine.

Remarque : CopyTo () n’est pas implémenté, vous pouvez créer la même idée pour le tableau.

 using System.Collections; using System.Collections.Generic; namespace UDF.MyDataLayer { internal class ListCastAdapter : IList where T : class where S : class { private List adaptee; public ListCastAdapter(List adaptee ) { this.adaptee = adaptee; } #region Implementation of IEnumerable public class EnumeratorCastAdapter : IEnumerator { private IEnumerator adaptee; public EnumeratorCastAdapter(IEnumerator adaptee) { this.adaptee = adaptee; } #region Implementation of IDisposable ///  /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. ///  /// 2 public void Dispose() { adaptee.Dispose(); } #endregion #region Implementation of IEnumerator ///  /// Advances the enumerator to the next element of the collection. ///  ///  /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. ///  /// The collection was modified after the enumerator was created. 2 public bool MoveNext() { return adaptee.MoveNext(); } ///  /// Sets the enumerator to its initial position, which is before the first element in the collection. ///  /// The collection was modified after the enumerator was created. 2 public void Reset() { adaptee.Reset(); } ///  /// Gets the element in the collection at the current position of the enumerator. ///  ///  /// The element in the collection at the current position of the enumerator. ///  public T Current { get { // needs to check if it is an Object or Value Type return adaptee.Current as T; } } ///  /// Gets the current element in the collection. ///  ///  /// The current element in the collection. ///  /// The enumerator is positioned before the first element of the collection or after the last element.2 object IEnumerator.Current { get { return Current; } } #endregion } ///  /// Returns an enumerator that iterates through the collection. ///  ///  /// A  that can be used to iterate through the collection. ///  /// 1 public IEnumerator GetEnumerator() { return new EnumeratorCastAdapter(adaptee.GetEnumerator()); } ///  /// Returns an enumerator that iterates through a collection. ///  ///  /// An  object that can be used to iterate through the collection. ///  /// 2 IEnumerator IEnumerable.GetEnumerator() { return adaptee.GetEnumerator(); } #endregion #region Implementation of ICollection ///  /// Adds an item to the . ///  /// The object to add to the .The  is read-only. public void Add(T item) { adaptee.Add(item as S); } ///  /// Removes all items from the . ///  /// The  is read-only.  public void Clear() { adaptee.Clear(); } ///  /// Determines whether the  contains a specific value. ///  ///  /// true if  is found in the ; otherwise, false. ///  /// The object to locate in the . public bool Contains(T item) { return adaptee.Contains(item as S); } ///  /// Copies the elements of the  to an , starting at a particular  index. ///  /// The one-dimensional  that is the destination of the elements copied from . The  must have zero-based indexing.The zero-based index in  at which copying begins. is null. is less than 0. is multidimensional.-or-The number of elements in the source  is greater than the available space from  to the end of the destination .-or-Type  cannot be cast automatically to the type of the destination . public void CopyTo(T[] array, int arrayIndex) { throw new System.NotImplementedException("Not Needed by Me, implement ArrayCastAdapter if needed"); } ///  /// Removes the first occurrence of a specific object from the . ///  ///  /// true if  was successfully removed from the ; otherwise, false. This method also returns false if  is not found in the original . ///  /// The object to remove from the .The  is read-only. public bool Remove(T item) { adaptee.Remove(item as S); } ///  /// Gets the number of elements contained in the . ///  ///  /// The number of elements contained in the . ///  public int Count { get { return adaptee.Count; } } ///  /// Gets a value indicating whether the  is read-only. ///  ///  /// true if the  is read-only; otherwise, false. ///  public bool IsReadOnly { get { return true; // change, to live on the edge } } #endregion #region Implementation of IList ///  /// Determines the index of a specific item in the . ///  ///  /// The index of  if found in the list; otherwise, -1. ///  /// The object to locate in the . public int IndexOf(T item) { return adaptee.IndexOf(item as S); } ///  /// Inserts an item to the  at the specified index. ///  /// The zero-based index at which  should be inserted.The object to insert into the . is not a valid index in the .The  is read-only. public void Insert(int index, T item) { adaptee.Insert(index, item as S); } ///  /// Removes the  item at the specified index. ///  /// The zero-based index of the item to remove. is not a valid index in the .The  is read-only. public void RemoveAt(int index) { adaptee.RemoveAt(index); } ///  /// Gets or sets the element at the specified index. ///  ///  /// The element at the specified index. ///  /// The zero-based index of the element to get or set. is not a valid index in the .The property is set and the  is read-only. public T this[int index] { get { return adaptee[index] as T; } set { adaptee[index] = value as S; } } #endregion } }