English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Operadores de conversión LINQ

El operador de conversión en LINQ se puede usar para convertir el tipo de elementos de una secuencia (conjunto). Los operadores de conversión se dividen en tres tipos:AsOperadores (AsEnumerable y AsQueryable),ToOperadores (ToArray, ToDictionary, ToList y ToLookup) yConversiónOperadores (Cast y OfType).

La tabla a continuación enumera todos los operadores de conversión.

MétodoDescripción
AsEnumerable

Devuelve la secuencia de entrada como IEnumerable < T>

AsQueryable

Convierte IEnumerable a IQueryable para simular proveedor de servicios de consulta remota

Cast

Convierte una colección no genérica en una colección genérica (IEnumerable a IEnumerable)

OfTypeFiltra la colección basada en el tipo especificado
ToArrayConvierte la colección en un array
ToDictionary

Coloca los elementos en Dictionary según la función selector de clave

ToList

Convierte la colección en List

ToLookupAgrupa los elementos en Lookup<TKey, TElement>

Métodos AsEnumerable y AsQueryable

Los métodos AsEnumerable y AsQueryable convierten el objeto de origen o lo convierten en IEnumerable <T> o IQueryable <T>.

Vea el siguiente ejemplo:

class Program
{
    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-type: {0}, typeof(T).Name);
        Console.WriteLine("Tipo real: {0}", obj.GetType().Name)}
    }
    static void Main(string[] args)
    {
        Student[] studentArray = { 
                new Student() { StudentID = 1, StudentName = "John", Age = 18 }
                new Student() { StudentID = 2, StudentName = "Steve", Age = 21 }
                new Student() { StudentID = 3, StudentName = "Bill", Age = 25 }
                new Student() { StudentID = 4, StudentName = "Ram", Age = 20 },
                new Student() { StudentID = 5, StudentName = "Ron", Age = 31 }
            }   
            
        ReportTypeProperties(studentArray);
        ReportTypeProperties(studentArray.AsEnumerable());
        ReportTypeProperties(studentArray.AsQueryable());   
    }
}
Salida:
Compile-Tipo de tiempo: Student[]
Tipo real: Student[]
Compile-Tipo de tiempo: IEnumerable`1
Tipo real: Student[]
Compile-type: IQueryable`1
Tipo real: EnumerableQuery`1

Como se muestra en el ejemplo anterior, los métodos AsEnumerable y AsQueryable convierten el tipo de tiempo de compilación en IEnumerable y IQueryable

Cast

La función de Cast es la misma que AsEnumerable<T>. Convierte el objeto de origen en IEnumerable<T>.

class Program
{
    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-type: {0}, typeof(T).Name);
        Console.WriteLine("Tipo real: {0}", obj.GetType().Name)}
    }
    static void Main(string[] args)
    {
        Student[] studentArray = { 
                new Student() { StudentID = 1, StudentName = "John", Age = 18 }
                new Student() { StudentID = 2, StudentName = "Steve", Age = 21 }
                new Student() { StudentID = 3, StudentName = "Bill", Age = 25 }
                new Student() { StudentID = 4, StudentName = "Ram", Age = 20 },
                new Student() { StudentID = 5, StudentName = "Ron", Age = 31 }
            }   
         
        ReportTypeProperties(studentArray);
        ReportTypeProperties(studentArray.Cast<Student>());
    }
}
Salida:
Compile-Tipo de tiempo: Student[]
Tipo real: Student[]
Compile-Tipo de tiempo: IEnumerable`1
Tipo real: Student[]
Compile-Tipo de tiempo: IEnumerable`1
Tipo real: Student[]
Compile-Tipo de tiempo: IEnumerable`1
Tipo real: Student[]

studentArray.Cast<Student>() es lo mismo que (IEnumerable<Student>)studentArray, pero Cast<Student>() tiene mejor legibilidad.

Operador To: ToArray(), ToList(), ToDictionary()

Como su nombre indica, los métodos ToArray(), ToList(), ToDictionary() convierten el objeto de origen en un array, una lista o un diccionario, respectivamente.

El operador To ejecuta la consulta. Fuerza al proveedor de consulta remota a ejecutar la consulta y obtener los resultados del origen de datos subyacente (como una base de datos SQL Server).

IList<string> strList = new List<string>() { 
                                            "One", 
                                            "Two", 
                                            "Three", 
                                            "Four", 
                                            "Three" 
                                            }
string[] strArray = strList.ToArray<string>();// Convertir una lista en un array
IList<string> list = strArray.ToList<string>(); // convierte un array en una lista

ToDictionary - Convertir una lista genérica en un diccionario genérico:

IList<Student> studentList = new List<Student>() { 
                    new Student() { StudentID = 1, NombreEstudiante = "John", edad = 18 }
                    new Student() { StudentID = 2, NombreEstudiante = "Steve", edad = 21 }
                    new Student() { StudentID = 3, NombreEstudiante = "Bill", edad = 18 }
                    new Student() { StudentID = 4, NombreEstudiante = "Ram", edad = 20 },
                    new Student() { StudentID = 5, NombreEstudiante = "Ron", edad = 21 } 
                }
//A continuación, se convierte la lista en un diccionario, donde StudentId es la clave
IDictionary<int, Student> studentDict = 
                                studentList.ToDictionary<Student, int>(s => s.StudentID); 
foreach(var key in studentDict.Keys)
	Console.WriteLine("Clave: {0}, Valor: ",1} 
                                key, (studentDict[key] as Student).StudentName);
Salida:
Clave: 1, Valor: John
Clave: 2, Valor: Steve
Clave: 3, Valor: Bill
Clave: 4, Valor: Ram
Clave: 5, Valor: Ron

La siguiente imagen muestra cómo studentDict contiene una key del ejemplo anterior-value de pares, donde key es StudentID y value es el objeto Student.

LINQ-Operador ToDictionary