English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O operador de conversão no LINQ pode ser usado para converter o tipo de elementos da sequência (conjunto). Os operadores de conversão são divididos em três tipos:AsOperadores (AsEnumerable e AsQueryable),ToOperadores (ToArray, ToDictionary, ToList e ToLookup) eConversãoOperadores (Cast e OfType).
A tabela a seguir lista todos os operadores de conversão.
Método | Descrição |
---|---|
AsEnumerable | Retornar a sequência de entrada como IEnumerable <T> |
AsQueryable | Converter IEnumerable para IQueryable para simular provedor de consulta remota |
Cast | Converter coleção não genérica para coleção genérica (IEnumerable para IEnumerable) |
OfType | Filtrar a coleção com base no tipo especificado |
ToArray | Converter a coleção para array |
ToDictionary | Colocar elementos no Dictionary com base na função seletora de chave |
ToList | Converter a coleção para List |
ToLookup | Agrupar elementos no Lookup<TKey, TElement> |
Os métodos AsEnumerable e AsQueryable convertem ou transformam o objeto de origem em IEnumerable <T> ou IQueryable <T>.
Veja os seguintes exemplos:
class Program { static void ReportTypeProperties<T>(T obj) { Console.WriteLine("Compile",-time type: {0} 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());
Compile-Tipo de tempo: Student[] Tipo real: Student[] Compile-Tipo de tempo: IEnumerable`1 Tipo real: Student[] Compile-Tipo real: IQueryable`1 Tipo real: EnumerableQuery`1
Como mostrado no exemplo acima, os métodos AsEnumerable e AsQueryable convertem o tipo de tempo de compilação para IEnumerable e IQueryable
A função do Cast é a mesma que a de AsEnumerable<T>. Ele força a conversão do objeto de origem para IEnumerable<T>.
class Program { static void ReportTypeProperties<T>(T obj) { Console.WriteLine("Compile",-time type: {0} 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>());
Compile-Tipo de tempo: Student[] Tipo real: Student[] Compile-Tipo de tempo: IEnumerable`1 Tipo real: Student[] Compile-Tipo de tempo: IEnumerable`1 Tipo real: Student[] Compile-Tipo de tempo: IEnumerable`1 Tipo real: Student[]
studentArray.Cast<Student>() é o mesmo que (IEnumerable<Student>)studentArray, mas Cast<Student>() é mais legível.
Como o próprio nome sugere, os métodos ToArray(), ToList(), ToDictionary() transformam o objeto de origem em um array, uma lista ou um dicionário, respectivamente.
O operador To força a execução da consulta. Ele força o provedor de consulta remoto a executar a consulta e a obter os resultados do provedor de dados subjacente (como um banco de dados SQL Server).
IList<string> strList = new List<string>() { "One", "Two", "Three", "Four", "Three" string[] strArray = strList.ToArray<string>();// Converta a lista em um array IList<string> list = strArray.ToList<string>(); // converte array em lista
ToDictionary - Converta lista genérica em um dicionário genérico:
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, NomeDoAluno = "John", idade = 18 } new Student() { StudentID = 2, NomeDoAluno = "Steve", idade = 21 } new Student() { StudentID = 3, NomeDoAluno = "Bill", idade = 18 } new Student() { StudentID = 4, NomeDoAluno = "Ram", idade = 20 }, new Student() { StudentID = 5, NomeDoAluno = "Ron", idade = 21 //A seguir, a lista será convertida em dicionário, onde StudentId é a chave IDictionary<int, Student> studentDict = studentList.ToDictionary<Student, int>(s => s.StudentID); foreach(var key in studentDict.Keys) Console.WriteLine("Chave: {0}, Valor: ",1 key, (studentDict[key] as Student).StudentName);
Chave: 1, Valor: John Chave: 2, Valor: Steve Chave: 3, Valor: Bill Chave: 4, Valor: Ram Chave: 5, Valor: Ron
A figura a seguir mostra como o studentDict contém uma chave da exemplo acima-par de valor, onde a chave é StudentID e o valor é o objeto Student.