Porady: zapytanie o znaki w ciągu (LINQ)
Ponieważ String klasy implementuje rodzajową IEnumerable interfejsu, wszystkie ciągi znaków można wyszukiwać jako sekwencję znaków.Jednakże nie jest to typowe zastosowanie LINQ.Dla złożonych wzorca operacji dopasowywania, użyj Regex klasy.
Przykład
Poniższy przykład kwerendy ciąg do określania liczby cyfr, które on zawiera.Należy zauważyć, że kwerenda jest "ponownie" po wykonaniu po raz pierwszy.Jest to możliwe, ponieważ sama kwerenda nie przechowuje żadnych rzeczywistych wyników.
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
*/
Kompilowanie kodu
Tworzenie Visual Studio projekt, który jest przeznaczony dla .NET Framework w wersji 3.5.Domyślnie projekt zawiera odwołanie do System.Core.dll i using dyrektywy (C#) lub Imports instrukcji (Visual Basic) dla obszaru nazw System.Linq.W języku C# projektów, należy dodać using dyrektywa obszaru nazw System.IO.
Skopiuj ten kod do projektu.
Naciśnij klawisz F5, aby skompilować i uruchomić program.
Naciśnij dowolny klawisz, aby zamknąć okno konsoli.
Zobacz też
Zadania
Porady: łączenie kwerend LINQ z wyrażeniami regularnymi