Condividi tramite


Procedura: ordinare o filtrare i dati di testo in base a qualsiasi parola o campo (LINQ)

Nell'esempio seguente viene illustrato come ordinare righe di testo strutturato, ad esempio valori delimitati da virgole, in base a qualsiasi campo nella riga. Il campo può essere specificato dinamicamente in fase di esecuzione. Si supponga che i campi in scores.csv rappresentino il numero ID di un studente, seguito da una serie di quattro punteggi del test.

Per creare un file contenente dati

Esempio

Class SortLines

    Shared Sub Main()
        Dim scores As String() = System.IO.File.ReadAllLines("../../../scores.csv")

        ' Change this to any value from 0 to 4 
        Dim sortField As Integer = 1

        Console.WriteLine("Sorted highest to lowest by field " & sortField)

        ' Demonstrates how to return query from a method. 
        ' The query is executed here. 
        For Each str As String In SortQuery(scores, sortField)
            Console.WriteLine(str)
        Next 

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

    End Sub 

    Shared Function SortQuery(
        ByVal source As IEnumerable(Of String), 
        ByVal num As Integer) As IEnumerable(Of String)

        Dim scoreQuery = From line In source 
                         Let fields = line.Split(New Char() {","}) 
                         Order By fields(num) Descending 
                         Select line

        Return scoreQuery
    End Function 
End Class 
' Output: 
' Sorted highest to lowest by field 1 
' 116, 99, 86, 90, 94 
' 120, 99, 82, 81, 79 
' 111, 97, 92, 81, 60 
' 114, 97, 89, 85, 82 
' 121, 96, 85, 91, 60 
' 122, 94, 92, 91, 91 
' 117, 93, 92, 80, 87 
' 118, 92, 90, 83, 78 
' 113, 88, 94, 65, 91 
' 112, 75, 84, 91, 39 
' 119, 68, 79, 88, 92 
' 115, 35, 72, 91, 70
public class SortLines
{
    static void Main()
    {
        // Create an IEnumerable data source 
        string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv");

        // Change this to any value from 0 to 4. 
        int sortField = 1;

        Console.WriteLine("Sorted highest to lowest by field [{0}]:", sortField);

        // Demonstrates how to return query from a method. 
        // The query is executed here. 
        foreach (string str in RunQuery(scores, sortField))
        {
            Console.WriteLine(str);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // Returns the query variable, not query results! 
    static IEnumerable<string> RunQuery(IEnumerable<string> source, int num)
    {
        // Split the string and sort on field[num] 
        var scoreQuery = from line in source
                         let fields = line.Split(',')
                         orderby fields[num] descending 
                         select line;

        return scoreQuery;
    }
}
/* Output (if sortField == 1):
   Sorted highest to lowest by field [1]:
    116, 99, 86, 90, 94
    120, 99, 82, 81, 79
    111, 97, 92, 81, 60
    114, 97, 89, 85, 82
    121, 96, 85, 91, 60
    122, 94, 92, 91, 91
    117, 93, 92, 80, 87
    118, 92, 90, 83, 78
    113, 88, 94, 65, 91
    112, 75, 84, 91, 39
    119, 68, 79, 88, 92
    115, 35, 72, 91, 70
 */

In questo esempio viene inoltre illustrato come restituire una variabile di query da un funzione (Visual Basic) o un metodo (C#).

Compilazione del codice

  • Creare un progetto di Visual Studio destinato a .NET Framework versione 3.5. Per impostazione predefinita, il progetto include un riferimento a System.Core.dll e una direttiva using (C#) o un'istruzione Imports (Visual Basic) per lo spazio dei nomi System.Linq. Nei progetti C# aggiungere una direttiva using per lo spazio dei nomi System.IO.

  • Copiare questo codice nel progetto.

  • Premere F5 per compilare ed eseguire il programma.

  • Premere un tasto per chiudere la finestra della console.

Vedere anche

Concetti

LINQ e stringhe