Cómo: Consultar un objeto ArrayList con LINQ

Actualización: noviembre 2007

Al utilizar LINQ para consultar colecciones IEnumerable no genéricas, como ArrayList, debe declarar explícitamente el tipo de la variable de rango para reflejar el tipo específico de los objetos de la colección. Por ejemplo, si tiene una estructura ArrayList de objetos Student, su cláusula from (C#) o From (Cláusula, Visual Basic) debería ser similar a la siguiente:

// C#
var query = from Student s in arrList
... 
'Visual Basic
Dim query = From student As Student In arrList _
...

Al especificar el tipo de la variable de rango, convierte cada elemento de ArrayList en Student.

Utilizar una variable de rango con un tipo declarado explícitamente en una expresión de consulta es equivalente a llamar al método Cast<TResult>. Cast<TResult> inicia una excepción si no se puede realizar la conversión de tipos especificada. Cast<TResult> y OfType<TResult> son los dos métodos de operador de consulta estándar que actúan en tipos IEnumerable no genéricos.

Ejemplo

En el ejemplo siguiente se muestra una consulta simple sobre ArrayList. Observe que en este ejemplo se utilizan inicializadores de objeto cuando el código llama al método Add, pero no es obligatorio.

Imports System.Collections
Imports System.Linq

Module Module1

    Public Class Student
        Public FirstName As String
        Public LastName As String
        Public Scores As Integer()
    End Class

    Sub Main()

        Dim student1 As New Student With {.FirstName = "Svetlana", _
                                     .LastName = "Omelchenko", _
                                     .Scores = New Integer() {98, 92, 81, 60}}
        Dim student2 As New Student With {.FirstName = "Claire", _
                                    .LastName = "O'Donnell", _
                                    .Scores = New Integer() {75, 84, 91, 39}}
        Dim student3 As New Student With {.FirstName = "Cesar", _
                                    .LastName = "Garcia", _
                                    .Scores = New Integer() {97, 89, 85, 82}}
        Dim student4 As New Student With {.FirstName = "Sven", _
                                    .LastName = "Mortensen", _
                                    .Scores = New Integer() {88, 94, 65, 91}}

        Dim arrList As New ArrayList()
        arrList.Add(student1)
        arrList.Add(student2)
        arrList.Add(student3)
        arrList.Add(student4)

        ' Use an explicit type for non-generic collections
        Dim query = From student As Student In arrList _
                    Where student.Scores(0) > 95 _
                    Select student

        For Each student As Student In query
            Console.WriteLine(student.LastName & ": " & student.Scores(0))
        Next
        ' Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub

End Module
' Output:
'   Omelchenko: 98
'   Garcia: 97
using System;
using System.Collections;
using System.Linq;

namespace NonGenericLINQ
{
    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int[] Scores { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arrList = new ArrayList();
            arrList.Add(
                new Student
                    {
                        FirstName = "Svetlana", LastName = "Omelchenko", Scores = new int[] { 98, 92, 81, 60 }
                    });
            arrList.Add(
                new Student
                    {
                        FirstName = "Claire", LastName = "O’Donnell", Scores = new int[] { 75, 84, 91, 39 }
                    });
            arrList.Add(
                new Student
                    {
                        FirstName = "Sven", LastName = "Mortensen", Scores = new int[] { 88, 94, 65, 91 }
                    });
            arrList.Add(
                new Student
                    {
                        FirstName = "Cesar", LastName = "Garcia", Scores = new int[] { 97, 89, 85, 82 }
                    });

            var query = from Student student in arrList
                        where student.Scores[0] > 95
                        select student;

            foreach (Student s in query)
                Console.WriteLine(s.LastName + ": " + s.Scores[0]);

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}
/* Output: 
    Omelchenko: 98
    Garcia: 97
*/

Vea también

Conceptos

LINQ to Objects