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

运算符转换LINQ

Gli operatori di conversione in LINQ possono essere utilizzati per convertire il tipo degli elementi di una sequenza (raccolta). Gli operatori di conversione sono suddivisi in tre categorie:AsOperatori (AsEnumerable e AsQueryable),ToOperatori (ToArray, ToDictionary, ToList e ToLookup) eConversioneOperatori (Cast e OfType).

La tabella seguente elenca tutti gli operatori di conversione.

MetodoDescrizione
AsEnumerable

Restituisci la sequenza di input come IEnumerable<T>

AsQueryable

AsQueryable

Cast

Converti una raccolta non generica in una raccolta generica (IEnumerable a IEnumerable)

OfTypeFiltra la raccolta in base a un tipo specificato
ToArrayConverti una raccolta in un array
ToDictionary

Inserisci gli elementi nel Dictionary in base a una funzione di selezione della chiave

ToList

Converti una raccolta in List

ToLookupAssegna gli elementi al Lookup<TKey, TElement>

Metodi AsEnumerable e AsQueryable

I metodi AsEnumerable e AsQueryable trasformano o convertono l'oggetto sorgente in IEnumerable <T> o IQueryable <T>.

Ecco un esempio:

class Program
{
    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-time type: {0}", typeof(T).Name);
        Console.WriteLine("Actual type: {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());   
    }
}
输出:
Tipo a compile-time: Student[]
Tipo effettivo: Student[]
Tipo a compile-time: IEnumerable`1
Tipo effettivo: Student[]
Compile-time type: IQueryable`1
Actual type: EnumerableQuery`1

Come mostrato nell'esempio, i metodi AsEnumerable e AsQueryable trasformano rispettivamente il tipo di compilazione in IEnumerable e IQueryable

Cast

L'azione del Cast è la stessa di AsEnumerable<T>. Esso trasforma l'oggetto sorgente in IEnumerable<T>.

class Program
{
    static void ReportTypeProperties<T>(T obj)
    {
        Console.WriteLine("Compile-time type: {0}", typeof(T).Name);
        Console.WriteLine("Actual type: {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>());
    }
}
输出:
Tipo a compile-time: Student[]
Tipo effettivo: Student[]
Tipo a compile-time: IEnumerable`1
Tipo effettivo: Student[]
Tipo a compile-time: IEnumerable`1
Tipo effettivo: Student[]
Tipo a compile-time: IEnumerable`1
Tipo effettivo: Student[]

studentArray.Cast<Student>() è uguale a (IEnumerable<Student>)studentArray, ma Cast<Student>() è più leggibile.

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

Come suggerisce il nome, i metodi ToArray(), ToList(), ToDictionary() trasformano l'oggetto sorgente in un array, una lista o un dizionario rispettivamente.

L'operatore To forza l'esecuzione della query. Costringe il provider remoto della query a eseguire la query e a ottenere i risultati dal sorgente dati di basso livello (ad esempio, database SQL Server).

IList<string> strList = new List<string>() { 
                                            "Uno", 
                                            "Due", 
                                            "Tre", 
                                            "Quattro", 
                                            "Tre" 
                                            };
string[] strArray = strList.ToArray<string>();// Converti la lista in un array
IList<string> list = strArray.ToList<string>(); // Converti l'array in una lista

ToDictionary - Converti una lista generica in un dizionario generico:

IList<Student> studentList = new List<Student>() { 
                    new Student() { StudentID = 1, StudentName = "John", age = 18 } ,
                    new Student() { StudentID = 2, StudentName = "Steve", age = 21 } ,
                    new Student() { StudentID = 3, StudentName = "Bill", age = 18 } ,
                    new Student() { StudentID = 4, StudentName = "Ram", age = 20 } ,
                    new Student() { StudentID = 5, StudentName = "Ron", age = 21 } 
                };
//以下将列表转换成字典,其中StudentId是键
IDictionary<int, Student> studentDict = 
                                studentList.ToDictionary<Student, int>(s => s.StudentID); 
foreach(var key in studentDict.Keys)
	Console.WriteLine("键: {0}, 值: {1}", 
                                key, (studentDict[key] as Student).StudentName);
输出:
键: 1, 值: John
键: 2, 值: Steve
键: 3, 值: Bill
键: 4, 值: Ram
键: 5, 值: Ron

以下图显示了上面示例中的studentDict如何包含一个键值对,其中键是StudentID,值是Student对象。

运算符 LINQ-ToDictionary