Cómo: Rellenar colecciones de objetos de varios orígenes (LINQ)

En este ejemplo se muestra cómo combinar datos de distintos orígenes en una secuencia de tipos nuevos.

NotaNota

No intente combinar datos en memoria o datos del sistema de archivos con datos que todavía estén en una base de datos.Este tipo de combinaciones entre dominios puede generar resultados sin definir, dadas las distintas maneras en las que se pueden definir las operaciones de combinación para las consultas de base de datos y otros tipos de orígenes.Existe además el riesgo de que este tipo de operación provoque una excepción de memoria insuficiente si la cantidad de datos de la base de datos es lo suficientemente grande.Para combinar datos de una base de datos con datos en memoria, llame primero a ToList o ToArray en la consulta de base de datos y, a continuación, realice la combinación con la colección devuelta.

Para crear el archivo de datos

Ejemplo

En el ejemplo siguiente se muestra cómo utilizar un tipo con nombre Student para almacenar los datos combinados de dos colecciones de cadenas en memoria que simulan datos de hoja de cálculo en formato .csv. La primera colección de cadenas representa los nombres e identificadores de los estudiantes y la segunda colección representa el identificador de estudiante (en la primera columna) y cuatro puntuaciones de examen. El identificador se usa como clave externa.

Class Student
    Public FirstName As String 
    Public LastName As String 
    Public ID As Integer 
    Public ExamScores As List(Of Integer)
End Class 

Class PopulateCollection

    Shared Sub Main()

        ' Merge content from spreadsheets into a list of Student objects. 

        ' These data files are defined in How to: Join Content from  
        ' Dissimilar Files (LINQ). 

        ' Each line of names.csv consists of a last name, a first name, and an 
        ' ID number, separated by commas. For example, Omelchenko,Svetlana,111 
        Dim names As String() = System.IO.File.ReadAllLines("../../../names.csv")

        ' Each line of scores.csv consists of an ID number and four test  
        ' scores, separated by commas. For example, 111, 97, 92, 81, 60 
        Dim scores As String() = System.IO.File.ReadAllLines("../../../scores.csv")

        ' The following query merges the content of two dissimilar spreadsheets  
        ' based on common ID values. 
        ' Multiple From clauses are used instead of a Join clause 
        ' in order to store the results of scoreLine.Split. 
        ' Note the dynamic creation of a list of integers for the 
        ' ExamScores member. We skip the first item in the split string  
        ' because it is the student ID, not an exam score. 
        Dim queryNamesScores = From nameLine In names
                          Let splitName = nameLine.Split(New Char() {","})
                          From scoreLine In scores
                          Let splitScoreLine = scoreLine.Split(New Char() {","})
                          Where splitName(2) = splitScoreLine(0)
                          Select New Student() With {
                               .FirstName = splitName(0), .LastName = splitName(1), .ID = splitName(2),
                               .ExamScores = (From scoreAsText In splitScoreLine Skip 1
                                             Select Convert.ToInt32(scoreAsText)).ToList()}

        ' Optional. Store the query results for faster access in future 
        ' queries. This could be useful with very large data files. 
        Dim students As List(Of Student) = queryNamesScores.ToList()

        ' Display each student's name and exam score average. 
        For Each s In students
            Console.WriteLine("The average score of " & s.FirstName & " " &
                              s.LastName & " is " & s.ExamScores.Average())
        Next 

        ' Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub 
End Class 

' Output:  
' The average score of Omelchenko Svetlana is 82.5 
' The average score of O'Donnell Claire is 72.25 
' The average score of Mortensen Sven is 84.5 
' The average score of Garcia Cesar is 88.25 
' The average score of Garcia Debra is 67 
' The average score of Fakhouri Fadi is 92.25 
' The average score of Feng Hanying is 88 
' The average score of Garcia Hugo is 85.75 
' The average score of Tucker Lance is 81.75 
' The average score of Adams Terry is 85.25 
' The average score of Zabokritski Eugene is 83 
' The average score of Tucker Michael is 92
class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public List<int> ExamScores { get; set; }
}

class PopulateCollection
{
    static void Main()
    {
        // These data files are defined in How to: Join Content from  
        // Dissimilar Files (LINQ). 

        // Each line of names.csv consists of a last name, a first name, and an 
        // ID number, separated by commas. For example, Omelchenko,Svetlana,111 
        string[] names = System.IO.File.ReadAllLines(@"../../../names.csv");

        // Each line of scores.csv consists of an ID number and four test  
        // scores, separated by commas. For example, 111, 97, 92, 81, 60 
        string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv");

        // Merge the data sources using a named type. 
        // var could be used instead of an explicit type. Note the dynamic 
        // creation of a list of ints for the ExamScores member. We skip  
        // the first item in the split string because it is the student ID,  
        // not an exam score.
        IEnumerable<Student> queryNamesScores =
            from nameLine in names
            let splitName = nameLine.Split(',')
            from scoreLine in scores
            let splitScoreLine = scoreLine.Split(',')
            where splitName[2] == splitScoreLine[0]
            select new Student()
            {
                FirstName = splitName[0],
                LastName = splitName[1],
                ID = Convert.ToInt32(splitName[2]),
                ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
                              select Convert.ToInt32(scoreAsText)).
                              ToList()
            };

        // Optional. Store the newly created student objects in memory 
        // for faster access in future queries. This could be useful with 
        // very large data files.
        List<Student> students = queryNamesScores.ToList();

        // Display each student's name and exam score average. 
        foreach (var student in students)
        {
            Console.WriteLine("The average score of {0} {1} is {2}.",
                student.FirstName, student.LastName,
                student.ExamScores.Average());
        }

        //Keep console window open in debug mode
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output: 
    The average score of Omelchenko Svetlana is 82.5.
    The average score of O'Donnell Claire is 72.25.
    The average score of Mortensen Sven is 84.5.
    The average score of Garcia Cesar is 88.25.
    The average score of Garcia Debra is 67.
    The average score of Fakhouri Fadi is 92.25.
    The average score of Feng Hanying is 88.
    The average score of Garcia Hugo is 85.75.
    The average score of Tucker Lance is 81.75.
    The average score of Adams Terry is 85.25.
    The average score of Zabokritski Eugene is 83.
    The average score of Tucker Michael is 92.
 */

En la cláusula select, se usa un inicializador de objeto para crear instancias de cada nuevo objeto Student utilizando los datos de los dos orígenes.

Si no es necesario almacenar los resultados de la consulta, los tipos anónimos pueden ser más adecuados que los tipos con nombre. Los tipos con nombre son necesarios si los resultados de la consulta se pasan fuera del método en el que ésta se ejecuta. El ejemplo siguiente realiza la misma tarea que el ejemplo anterior, pero utiliza tipos anónimos en lugar de tipos con nombre:

' Merge the data by using an anonymous type.  
' Note the dynamic creation of a list of integers for the 
' ExamScores member. We skip 1 because the first string 
' in the array is the student ID, not an exam score. 
Dim queryNamesScores2 =
    From nameLine In names
    Let splitName = nameLine.Split(New Char() {","})
    From scoreLine In scores
    Let splitScoreLine = scoreLine.Split(New Char() {","})
    Where splitName(2) = splitScoreLine(0)
    Select New With
           {.Last = splitName(0),
            .First = splitName(1),
            .ExamScores = (From scoreAsText In splitScoreLine Skip 1
                           Select Convert.ToInt32(scoreAsText)).ToList()}

' Display each student's name and exam score average. 
For Each s In queryNamesScores2
    Console.WriteLine("The average score of " & s.First & " " &
                      s.Last & " is " & s.ExamScores.Average())
Next
// Merge the data sources by using an anonymous type. 
// Note the dynamic creation of a list of ints for the 
// ExamScores member. We skip 1 because the first string 
// in the array is the student ID, not an exam score. 
var queryNamesScores2 =
    from nameLine in names
    let splitName = nameLine.Split(',')
    from scoreLine in scores
    let splitScoreLine = scoreLine.Split(',')
    where splitName[2] == splitScoreLine[0]
    select new
    {
        First = splitName[0],
        Last = splitName[1],
        ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
                      select Convert.ToInt32(scoreAsText))
                      .ToList()
    };

// Display each student's name and exam score average. 
foreach (var student in queryNamesScores2)
{
    Console.WriteLine("The average score of {0} {1} is {2}.",
        student.First, student.Last, student.ExamScores.Average());
}

Compilar el código

  • Siga las instrucciones descritas en Cómo: Combinar contenido de archivos no similares (LINQ) para configurar los archivos de código fuente.

  • Cree un proyecto de Visual Studio dirigido a .NET Framework 3.5 o posterior. De manera predeterminada, el proyecto incluye una referencia a System.Core.dll y una directiva using (C#) o una instrucción Imports (Visual Basic) para el espacio de nombres System.Linq.

  • Copie este código en el proyecto.

  • Presione F5 para compilar y ejecutar el programa.

  • Presione cualquier tecla para salir de la ventana de consola.

Vea también

Referencia

Inicializadores de objeto y de colección (Guía de programación de C#)

Tipos anónimos (Guía de programación de C#)

Conceptos

LINQ y cadenas