Поделиться через


Практическое руководство. Запрос знаков в строке (LINQ)

Поскольку класс String реализует универсальный интерфейс IEnumerable, любая строка может запрашиваться как последовательность знаков. Однако это не является распространенным применением LINQ. Для операций соответствия сложному шаблону используйте класс Regex.

Пример

В следующем примере выполняется запрос к строке для определения в ней числа цифр. Обратите внимание, что после первого выполнения запрос "используется повторно". Это возможно, поскольку сам запрос не хранит фактических результатов.

Class QueryAString

    Shared Sub Main()

        ' A string is an IEnumerable data source. 
        Dim aString As String = "ABCDE99F-J74-12-89A" 

        ' Select only those characters that are numbers 
        Dim stringQuery = From ch In aString 
                          Where Char.IsDigit(ch) 
                          Select ch
        ' Execute the query 
        For Each c As Char In stringQuery
            Console.Write(c & " ")
        Next 

        ' Call the Count method on the existing query. 
        Dim count As Integer = stringQuery.Count()
        Console.WriteLine(System.Environment.NewLine & "Count = " & count)

        ' Select all characters before the first '-' 
        Dim stringQuery2 = aString.TakeWhile(Function(c) c <> "-")

        ' Execute the second query 
        For Each ch In stringQuery2
            Console.Write(ch)
        Next

        Console.WriteLine(System.Environment.NewLine & "Press any key to exit")
        Console.ReadKey()
    End Sub 
End Class 
' Output: 
' 9 9 7 4 1 2 8 9  
' Count = 8 
' ABCDE99F
class QueryAString
{
    static void Main()
    {
        string aString = "ABCDE99F-J74-12-89A";

        // Select only those characters that are numbers
        IEnumerable<char> stringQuery =
          from ch in aString
          where Char.IsDigit(ch)
          select ch;

        // Execute the query 
        foreach (char c in stringQuery)
            Console.Write(c + " ");

        // Call the Count method on the existing query. 
        int count = stringQuery.Count();
        Console.WriteLine("Count = {0}", count);

        // Select all characters before the first '-'
        IEnumerable<char> stringQuery2 = aString.TakeWhile(c => c != '-');

        // Execute the second query 
        foreach (char c in stringQuery2)
            Console.Write(c);

        Console.WriteLine(System.Environment.NewLine + "Press any key to exit");
        Console.ReadKey();
    }
}
/* Output:
  Output: 9 9 7 4 1 2 8 9
  Count = 8
  ABCDE99F
*/

Компиляция кода

  • Создайте проект Visual Studio, предназначенный для .NET Framework версии 3.5. По умолчанию в проекте имеются ссылка на файл System.Core.dll и директива using (C#) или оператор Imports (Visual Basic) для пространства имен System.Linq. При работе с проектами C# добавьте директиву using для пространства имен System.IO.

  • Скопируйте этот код в проект.

  • Нажмите клавишу F5, чтобы скомпилировать и выполнить программу.

  • Нажмите любую клавишу для выхода из окна консоли.

См. также

Задачи

Практическое руководство. Объединение запросов LINQ с регулярными выражениями

Основные понятия

LINQ и строки