2010-06-24 12 views
5

Cómo recuperar Objetos y sus miembros de la lista de matrices en C#.Cómo recuperar Objetos de la lista de arrays en C#

+0

Si está acostumbrado a Java, es posible que desee saber que ArrayList no es lo mismo que en Java. Hay muchos otros tipos de colecciones en la Lista C# es tipo seguro por ejemplo. –

Respuesta

15

¿Te refieres a esto?

ArrayList list = new ArrayList(); 
YourObject myObject = new YourObject(); 

list.Add(myObject);  

YourObject obj = (YourObject)list[0]; 

Para bucle a través de:

foreach(object o in list) 
{ 
    YourObject myObject = (YourObject)o; 
    ....... 
} 

Información sobre ArrayList

2

Aquí está un ejemplo de una simple ArrayList ser poblado con un nuevo objeto KeyValuePair. Luego retiro el objeto de ArrayList, lo vuelvo a poner en su tipo original y accedo a su propiedad.

var testObject = new KeyValuePair<string, string>("test", "property"); 
var list = new ArrayList(); 
list.Add(testObject); 
var fetch = (KeyValuePair<string, string>)list[0]; 
var endValue = fetch.Value; 
0

También puede utilizar los métodos de extensión:

ArrayList list = new ArrayList(); 
// If all objects in the list are of the same type 
IEnumerable<MyObject> myenumerator = list.Cast<MyObject>(); 
// Only get objects of a certain type, ignoring others 
IEnumerable<MyObject> myenumerator = list.OfType<MyObject>(); 

O si usted no está utilizando una nueva versión de .Net, comprobar el tipo de objeto y moldeada usando es/as

list[0] is MyObject; // returns true if it's an MyObject 
list[0] as MyObject; // returns the MyObject if it's a MyObject, or null if it's something else 

Editar: Pero si está utilizando una versión más reciente de .Net ...

Le sugiero que use las colecciones genéricas en Sistema .Collections.Generic

var list = new List<MyObject>(); // The list is constructed to work on types of MyObject 
MyObject obj = list[0]; 
list.Add(new AnotherObject()); // Compilation fail; AnotherObject is not MyObject 
3
object[] anArray = arrayListObject.ToArray(); 
    for(int i = 0; i < anArray.Length; i++) 
     Console.WriteLine((MyType)anArray[i]).PropertyName); 
+0

Realizo esta sencilla recomendación porque este usuario marcó su pregunta como principiante. Una vez que el OP comprende ArrayList, puede pasar a los genéricos y concentrarse solo en aprender genéricos. –

1

Debe utilizar colecciones genéricas para esto. Use el ArrayList genérico para que no tenga que lanzar el objeto cuando está tratando de sacarlo de la matriz.

+0

Esto es C#. No Java. –

Cuestiones relacionadas