Share via


Cómo: Dividir un archivo en varios mediante el uso de grupos (LINQ)

En este ejemplo se muestra una forma de combinar el contenido de dos archivos y crear después un conjunto de archivos nuevos que organicen los datos de manera distinta.

Para crear los archivos de datos

  1. Copie estos nombres en un archivo de texto que se denomine names1.txt y guárdelo en la carpeta de la solución:

    Bankov, Peter
    Holm, Michael
    Garcia, Hugo
    Potra, Cristina
    Noriega, Fabricio
    Aw, Kam Foo
    Beebe, Ann
    Toyoshima, Tim
    Guy, Wey Yuan
    Garcia, Debra
    
  2. Copie estos nombres en un archivo de texto que se denomine names2.txt y guárdelo en la carpeta de la solución. Observe que los dos archivos tienen algunos nombres en común.

    Liu, Jinghao
    Bankov, Peter
    Holm, Michael
    Garcia, Hugo
    Beebe, Ann
    Gilchrist, Beth
    Myrcha, Jacek
    Giakoumakis, Leo
    McLin, Nkenge
    El Yassir, Mehdi
    

Ejemplo

Class SplitWithGroups

    Shared Sub Main()

        Dim fileA As String() = System.IO.File.ReadAllLines("../../../names1.txt")
        Dim fileB As String() = System.IO.File.ReadAllLines("../../../names2.txt")

        ' Concatenate and remove duplicate names based on 
        Dim mergeQuery As IEnumerable(Of String) = fileA.Union(fileB)

        ' Group the names by the first letter in the last name 
        Dim groupQuery = From name In mergeQuery 
                     Let n = name.Split(New Char() {","}) 
                     Order By n(0) 
                     Group By groupKey = n(0)(0) 
                     Into groupName = Group

        ' Create a new file for each group that was created 
        ' Note that nested foreach loops are required to access 
        ' individual items with each group. 
        For Each gGroup In groupQuery
            Dim fileName As String = "..'..'..'testFile_" & gGroup.groupKey & ".txt" 
            Dim sw As New System.IO.StreamWriter(fileName)
            Console.WriteLine(gGroup.groupKey)
            For Each item In gGroup.groupName
                Console.WriteLine("   " & item.name)
                sw.WriteLine(item.name)
            Next
            sw.Close()
        Next 

        ' Keep console window open in debug mode.
        Console.WriteLine("Files have been written. Press any key to exit.")
        Console.ReadKey()

    End Sub 
End Class 
' Console Output: 
' A 
'    Aw, Kam Foo 
' B 
'    Bankov, Peter 
'    Beebe, Ann 
' E 
'    El Yassir, Mehdi 
' G 
'    Garcia, Hugo 
'    Garcia, Debra 
'    Giakoumakis, Leo 
'    Gilchrist, Beth 
'    Guy, Wey Yuan 
' H 
'    Holm, Michael 
' L 
'    Liu, Jinghao 
' M 
'    McLin, Nkenge 
'    Myrcha, Jacek 
' N 
'    Noriega, Fabricio 
' P 
'    Potra, Cristina 
' T 
'    Toyoshima, Tim
class SplitWithGroups
{
    static void Main()
    {
        string[] fileA = System.IO.File.ReadAllLines(@"../../../names1.txt");
        string[] fileB = System.IO.File.ReadAllLines(@"../../../names2.txt");

        // Concatenate and remove duplicate names based on 
        // default string comparer 
        var mergeQuery = fileA.Union(fileB);

        // Group the names by the first letter in the last name. 
        var groupQuery = from name in mergeQuery
                         let n = name.Split(',')
                         group name by n[0][0] into g
                         orderby g.Key
                         select g;

        // Create a new file for each group that was created 
        // Note that nested foreach loops are required to access 
        // individual items with each group. 
        foreach (var g in groupQuery)
        {
            // Create the new file name. 
            string fileName = @"../../../testFile_" + g.Key + ".txt";

            // Output to display.
            Console.WriteLine(g.Key);

            // Write file. 
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName))
            {
                foreach (var item in g)
                {
                    sw.WriteLine(item);
                    // Output to console for example purposes.
                    Console.WriteLine("   {0}", item);
                }
            }
        }
        // Keep console window open in debug mode.
        Console.WriteLine("Files have been written. Press any key to exit");
        Console.ReadKey();
    }
}
/* Output: 
    A
       Aw, Kam Foo
    B
       Bankov, Peter
       Beebe, Ann
    E
       El Yassir, Mehdi
    G
       Garcia, Hugo
       Guy, Wey Yuan
       Garcia, Debra
       Gilchrist, Beth
       Giakoumakis, Leo
    H
       Holm, Michael
    L
       Liu, Jinghao
    M
       Myrcha, Jacek
       McLin, Nkenge
    N
       Noriega, Fabricio
    P
       Potra, Cristina
    T
       Toyoshima, Tim
 */

El programa escribe un archivo independiente para cada grupo en la misma carpeta que los archivos de datos.

Compilar el código

  • Cree un proyecto de Visual Studio dirigido a .NET Framework versión 3.5. 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. En los proyectos de C#, agregue una directiva using para el espacio de nombres System.IO.

  • 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

Conceptos

LINQ y cadenas

LINQ y directorios de archivos