如何:查詢字串中的字元 (LINQ)
因為 String 類別 (Class) 實作泛型 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
*/
編譯程式碼
建立一個以 .NET Framework 3.5 版為目標的 Visual Studio 專案。 專案預設會含 System.Core.dll 的參考,以及 System.Linq 命名空間 (Namespace) 的 using 指示詞 (C#) 或 Imports 陳述式 (Visual Basic)。 請在 C# 專案中,加入 System.IO 命名空間的 using 指示詞。
請將這段程式碼複製到您的專案,
按 F5 編譯和執行程式。
按任何鍵離開主控台視窗。