String String String String Class

定義

以一連串的 UTF-16 字碼單位表示文字。Represents text as a sequence of UTF-16 code units.

public ref class String sealed : ICloneable, IComparable, IComparable<System::String ^>, IConvertible, IEquatable<System::String ^>, System::Collections::Generic::IEnumerable<char>
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class String : ICloneable, IComparable, IComparable<string>, IConvertible, IEquatable<string>, System.Collections.Generic.IEnumerable<char>
type string = class
    interface IComparable
    interface ICloneable
    interface IConvertible
    interface IEnumerable
    interface IComparable<string>
    interface seq<char>
    interface IEquatable<string>
Public NotInheritable Class String
Implements ICloneable, IComparable, IComparable(Of String), IConvertible, IEnumerable(Of Char), IEquatable(Of String)
繼承
StringStringStringString
屬性
實作

備註

字串是用來代表文字字元的循序集合。A string is a sequential collection of characters that is used to represent text. AString物件是循序集合System.Char物件來代表的字串;System.Char物件會對應至的 utf-16 字碼單位。A String object is a sequential collection of System.Char objects that represent a string; a System.Char object corresponds to a UTF-16 code unit. String物件是循序集合的內容System.Char物件和值是不可變 (亦即,它是唯讀)。The value of the String object is the content of the sequential collection of System.Char objects, and that value is immutable (that is, it is read-only). 字串的不變性的相關資訊,請參閱的不變性和 StringBuilder 類別本主題稍後的章節。For more information about the immutability of strings, see the Immutability and the StringBuilder class section later in this topic. 大小上限String物件在記憶體中的是 2 GB 的資料或大約 1 億個字元。The maximum size of a String object in memory is 2GB, or about 1 billion characters.

注意

此文章中的某些 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 請選取 [執行] 按鈕 (若該按鈕存在) 以在互動式視窗中執行範例。When present, select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

本節內容:In this section:

具現化字串物件 Instantiating a String object
Char 物件和 Unicode 字元 Char objects and Unicode characters
字串及 Unicode 標準 Strings and The Unicode Standard
字串和內嵌的 null 字元 Strings and embedded null characters
字串和索引 Strings and indexes
Null 字串和空字串 Null strings and empty strings
不變性和 StringBuilder 類別 Immutability and the StringBuilder class
序數與文化特性的作業 Ordinal vs. culture-sensitive operations
正規化 Normalization
依類別目錄的字串作業String operations by category

具現化字串物件Instantiating a String object

您可以具現化String物件如下:You can instantiate a String object in the following ways:

  • 字串常值,指派String變數。By assigning a string literal to a String variable. 這是最常用的方法,來建立字串。This is the most commonly used method for creating a string. 下列範例會使用指派來建立數個字串。The following example uses assignment to create several strings. 請注意,在 C# 中,因為反斜線 (\) 會逸出字元、 必須逸出字串中的常值反斜線或整個字串必須是@-quoted。Note that in C#, because the backslash (\) is an escape character, literal backslashes in a string must be escaped or the entire string must be @-quoted.

    using namespace System;
    
    void main()
    {
       String^ string1 = "This is a string created by assignment.";
       Console::WriteLine(string1);
       String^ string2a = "The path is C:\\PublicDocuments\\Report1.doc";
       Console::WriteLine(string2a);
    }
    // The example displays the following output: 
    //       This is a string created by assignment. 
    //       The path is C:\PublicDocuments\Report1.doc 
    
    string string1 = "This is a string created by assignment.";
    Console.WriteLine(string1);
    string string2a = "The path is C:\\PublicDocuments\\Report1.doc";
    Console.WriteLine(string2a);
    string string2b = @"The path is C:\PublicDocuments\Report1.doc";
    Console.WriteLine(string2b);
    // The example displays the following output:
    //       This is a string created by assignment.
    //       The path is C:\PublicDocuments\Report1.doc
    //       The path is C:\PublicDocuments\Report1.doc      
    
    Dim string1 As String = "This is a string created by assignment."
    Console.WriteLine(string1)
    Dim string2 As String = "The path is C:\PublicDocuments\Report1.doc"
    Console.WriteLine(string2)
    ' The example displays the following output:
    '       This is a string created by assignment.
    '       The path is C:\PublicDocuments\Report1.doc      
    
  • 藉由呼叫String類別建構函式。By calling a String class constructor. 下列範例會產生字串,藉由呼叫類別建構函式。The following example instantiates strings by calling several class constructors. 請注意,某些建構函式會包含字元陣列或做為參數的帶正負號的位元組陣列的指標。Note that some of the constructors include pointers to character arrays or signed byte arrays as parameters. Visual Basic 不支援這些建構函式的呼叫。Visual Basic does not support calls to these constructors. 如需詳細資訊String建構函式,請參閱String摘要的建構函式。For detailed information about String constructors, see the String constructor summary.

    using namespace System;
    
    void main()
    {
       wchar_t chars[5] = L"word";
       char bytes[6] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 };
    
       // Create a string from a character array. 
       String^ string1 = gcnew String(chars);
       Console::WriteLine(string1);
    
       // Create a string that consists of a character repeated 20 times. 
       String^ string2 = gcnew String('c', 20);
       Console::WriteLine(string2);
    
       String^ stringFromBytes = nullptr;
       String^ stringFromChars = nullptr;
    
       char * pbytes = &bytes[0];
       // Create a string from a pointer to a signed byte array.
       stringFromBytes = gcnew String(pbytes);
    
       wchar_t* pchars =  &chars[0];
       // Create a string from a pointer to a character array.
       stringFromChars = gcnew String(pchars);
    
       Console::WriteLine(stringFromBytes);
       Console::WriteLine(stringFromChars);
       Console::ReadLine();
    }
    // The example displays the following output: 
    //       word 
    //       cccccccccccccccccccc 
    //       ABCDE 
    //       word  
    
    char[] chars = { 'w', 'o', 'r', 'd' };
    sbyte[] bytes = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x00 };
    
    // Create a string from a character array.
    string string1 = new string(chars);
    Console.WriteLine(string1);
    
    // Create a string that consists of a character repeated 20 times.
    string string2 = new string('c', 20);
    Console.WriteLine(string2);
    
    string stringFromBytes = null;
    string stringFromChars = null;
    unsafe
    {
       fixed (sbyte* pbytes = bytes)
       {
          // Create a string from a pointer to a signed byte array.
          stringFromBytes = new string(pbytes);
       }
       fixed (char* pchars = chars)
       {
          // Create a string from a pointer to a character array.
          stringFromChars = new string(pchars);
       }
    }
    Console.WriteLine(stringFromBytes);
    Console.WriteLine(stringFromChars);
    // The example displays the following output:
    //       word
    //       cccccccccccccccccccc
    //       ABCDE
    //       word  
    
    Dim chars() As Char = { "w"c, "o"c, "r"c, "d"c }
    
    ' Create a string from a character array.
    Dim string1 As New String(chars)
    Console.WriteLine(string1)
    
    ' Create a string that consists of a character repeated 20 times.
    Dim string2 As New String("c"c, 20)
    Console.WriteLine(string2)
    ' The example displays the following output:
    '       word
    '       cccccccccccccccccccc      
    
  • 使用字串串連運算子 (+ C# 和 (& s) 或 + 在 Visual Basic 中) 從任何組合建立單一字串String執行個體和字串常值。By using the string concatenation operator (+ in C# and & or + in Visual Basic) to create a single string from any combination of String instances and string literals. 下列範例說明如何使用字串串連運算子。The following example illustrates the use of the string concatenation operator.

    String^ string1 = "Today is " + DateTime::Now.ToString("D") + ".";
    Console::WriteLine(string1);
    
    String^ string2 = "This is one sentence. " + "This is a second. ";
    string2 += "This is a third sentence.";
    Console::WriteLine(string2);
    // The example displays output like the following: 
    //    Today is Tuesday, July 06, 2011. 
    //    This is one sentence. This is a second. This is a third sentence.
    
    string string1 = "Today is " + DateTime.Now.ToString("D") + ".";
    Console.WriteLine(string1);
    
    string string2 = "This is one sentence. " + "This is a second. ";
    string2 += "This is a third sentence.";
    Console.WriteLine(string2);
    // The example displays output like the following:
    //    Today is Tuesday, July 06, 2011.
    //    This is one sentence. This is a second. This is a third sentence.
    
    Dim string1 As String = "Today is " + Date.Now.ToString("D") + "."  
    Console.WriteLine(string1)
    Dim string2 As String = "This is one sentence. " + "This is a second. "
    string2 += "This is a third sentence."
    Console.WriteLine(string2)      
    ' The example displays output like the following:
    '    Today is Tuesday, July 06, 2011.
    '    This is one sentence. This is a second. This is a third sentence.
    
  • 擷取屬性或呼叫的方法,傳回的字串。By retrieving a property or calling a method that returns a string. 下列範例使用的方法String類別,以從較大的字串擷取子字串。The following example uses the methods of the String class to extract a substring from a larger string.

    String^ sentence = "This sentence has five words.";
    // Extract the second word.
    int startPosition = sentence->IndexOf(" ") + 1;
    String^ word2 = sentence->Substring(startPosition, 
                                        sentence->IndexOf(" ", startPosition) - startPosition);
    Console::WriteLine("Second word: " + word2);
    
    string sentence = "This sentence has five words.";
    // Extract the second word.
    int startPosition = sentence.IndexOf(" ") + 1;
    string word2 = sentence.Substring(startPosition,
                                      sentence.IndexOf(" ", startPosition) - startPosition);
    Console.WriteLine("Second word: " + word2);
    // The example displays the following output:
    //       Second word: sentence
    
    Dim sentence As String = "This sentence has five words."
    ' Extract the second word.
    Dim startPosition As Integer = sentence.IndexOf(" ") + 1
    Dim word2 As String = sentence.Substring(startPosition, 
                                             sentence.IndexOf(" ", startPosition) - startPosition) 
    Console.WriteLine("Second word: " + word2)
    ' The example displays the following output:
    '       Second word: sentence
    
  • 藉由呼叫格式化方法來將值或物件轉換為其字串表示。By calling a formatting method to convert a value or object to its string representation. 下列範例會使用複合格式內嵌的兩個物件的字串表示轉換為字串的功能。The following example uses the composite formatting feature to embed the string representation of two objects into a string.

    DateTime^ dateAndTime = gcnew DateTime(2011, 7, 6, 7, 32, 0);
    Double temperature = 68.3;
    String^ result = String::Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.",
                                   dateAndTime, temperature);
    Console::WriteLine(result);
    // The example displays the following output: 
    //       At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.      
    
    DateTime dateAndTime = new DateTime(2011, 7, 6, 7, 32, 0);
    double temperature = 68.3;
    string result = String.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.",
                                  dateAndTime, temperature);
    Console.WriteLine(result);
    // The example displays the following output:
    //       At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.      
    
    Dim dateAndTime As DateTime = #07/06/2011 7:32:00AM#
    Dim temperature As Double = 68.3
    Dim result As String = String.Format("At {0:t} on {0:D}, the temperature was {1:F1} degrees Fahrenheit.",
                                         dateAndTime, temperature)
    Console.WriteLine(result)
    ' The example displays the following output:
    '       At 7:32 AM on Wednesday, July 06, 2011, the temperature was 68.3 degrees Fahrenheit.      
    

Char 物件和 Unicode 字元Char objects and Unicode characters

在字串中的每個字元是由 Unicode 純量值,也稱為 Unicode 字碼指標或 Unicode 字元的序數 (數值) 定義。Each character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. 每個字碼指標會使用 utf-16 編碼,編碼,而且會以編碼方式的每個元素的數值表示Char物件。Each code point is encoded by using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a Char object.

注意

請注意,因為String執行個體包含循序集合的 utf-16 字碼單位,就可以建立String不是語式正確的 Unicode 字串的物件。Note that, because a String instance consists of a sequential collection of UTF-16 code units, it is possible to create a String object that is not a well-formed Unicode string. 比方說,就可以建立沒有對應的高 surrogate 的低 surrogate 的字串。For example, it is possible to create a string that has a low surrogate without a corresponding high surrogate. 雖然某些方法,例如編碼和解碼中的物件的方法System.Text命名空間,可能會執行檢查,以確保字串格式不正確,String類別成員不確定字串的格式正確。Although some methods, such as the methods of encoding and decoding objects in the System.Text namespace, may performs checks to ensure that strings are well-formed, String class members don't ensure that a string is well-formed.

單一Char物件通常代表單一字碼指標,也就是值的數值Char等於字碼指標。A single Char object usually represents a single code point; that is, the numeric value of the Char equals the code point. 例如,字碼指標"的字元 a"是 u+25ce 0061。For example, the code point for the character "a" is U+0061. 不過,程式碼點可能需要多個編碼項目 (一個以上Char物件)。However, a code point might require more than one encoded element (more than one Char object). Unicode 標準會定義兩種類型的字元對應至多個Char物件: graphemes,並對應至 Unicode 的增補平面中的字元的 Unicode 補充的字碼指標。The Unicode standard defines two types of characters that correspond to multiple Char objects: graphemes, and Unicode supplementary code points that correspond to characters in the Unicode supplementary planes.

  • 簇被以基底字元,後面接著一或多個組合的字元。A grapheme is represented by a base character followed by one or more combining characters. 比方說,表示的字元 äChar物件,其字碼指標為 U + 0061 後面的Char物件,其字碼指標為 U + 0308年。For example, the character ä is represented by a Char object whose code point is U+0061 followed by a Char object whose code point is U+0308. 此字元也可以定義由單一Char具有 U + 00E4 字碼指標的物件。This character can also be defined by a single Char object that has a code point of U+00E4. 如下列範例所示,區分文化特性比較相等表示這些兩種表示法相等,雖然一般的序數比較則否。As the following example shows, a culture-sensitive comparison for equality indicates that these two representations are equal, although an ordinary ordinal comparison does not. 不過,如果兩個字串會正規化,序數比較也會指出它們是否相等。However, if the two strings are normalized, an ordinal comparison also indicates that they are equal. (如需有關如何將正規化字串的詳細資訊,請參閱正規化一節。)(For more information on normalizing strings, see the Normalization section.)

    using namespace System;
    using namespace System::Globalization;
    using namespace System::IO;
    
    void main()
    {
       StreamWriter^ sw = gcnew StreamWriter(".\\graphemes.txt");
       String^ grapheme = L"a" + L"\u0308";
       sw->WriteLine(grapheme);
    
       String^ singleChar = "\u00e4";
       sw->WriteLine(singleChar);
    
       sw->WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar, 
                      String::Equals(grapheme, singleChar, 
                                  StringComparison::CurrentCulture));
       sw->WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar, 
                      String::Equals(grapheme, singleChar, 
                                  StringComparison::Ordinal));
       sw->WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar, 
                      String::Equals(grapheme->Normalize(), 
                                  singleChar->Normalize(), 
                                  StringComparison::Ordinal));
       sw->Close(); 
    }
    // The example produces the following output: 
    //       ä 
    //       ä 
    //       ä = ä (Culture-sensitive): True 
    //       ä = ä (Ordinal): False 
    //       ä = ä (Normalized Ordinal): True
    
    using System;
    using System.Globalization;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\graphemes.txt");
          string grapheme = "\u0061\u0308";
          sw.WriteLine(grapheme);
          
          string singleChar = "\u00e4";
          sw.WriteLine(singleChar);
                
          sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar, 
                       String.Equals(grapheme, singleChar, 
                                     StringComparison.CurrentCulture));
          sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar, 
                       String.Equals(grapheme, singleChar, 
                                     StringComparison.Ordinal));
          sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar, 
                       String.Equals(grapheme.Normalize(), 
                                     singleChar.Normalize(), 
                                     StringComparison.Ordinal));
          sw.Close(); 
       }
    }
    // The example produces the following output:
    //       ä
    //       ä
    //       ä = ä (Culture-sensitive): True
    //       ä = ä (Ordinal): False
    //       ä = ä (Normalized Ordinal): True
    
    Imports System.Globalization
    Imports System.IO
    
    Module Example
       Public Sub Main()
          Dim sw As New StreamWriter(".\graphemes.txt")
          Dim grapheme As String = ChrW(&H0061) + ChrW(&h0308)
          sw.WriteLine(grapheme)
          
          Dim singleChar As String = ChrW(&h00e4)
          sw.WriteLine(singleChar)
                
          sw.WriteLine("{0} = {1} (Culture-sensitive): {2}", grapheme, singleChar, 
                       String.Equals(grapheme, singleChar, 
                                     StringComparison.CurrentCulture))
          sw.WriteLine("{0} = {1} (Ordinal): {2}", grapheme, singleChar, 
                       String.Equals(grapheme, singleChar, 
                                     StringComparison.Ordinal))
          sw.WriteLine("{0} = {1} (Normalized Ordinal): {2}", grapheme, singleChar, 
                       String.Equals(grapheme.Normalize(), 
                                     singleChar.Normalize(), 
                                     StringComparison.Ordinal))
          sw.Close() 
       End Sub
    End Module
    ' The example produces the following output:
    '       ä
    '       ä
    '       ä = ä (Culture-sensitive): True
    '       ä = ä (Ordinal): False
    '       ä = ä (Normalized Ordinal): True
    
  • 增補的字碼指標 (surrogate 字組) 由 UnicodeChar後面接著物件,其字碼指標為為高 surrogateChar物件,其字碼指標為低 surrogate。A Unicode supplementary code point (a surrogate pair) is represented by a Char object whose code point is a high surrogate followed by a Char object whose code point is a low surrogate. 高 surrogate 範圍是從 U+D800 到 U + DBFF 的程式碼單元。The code units of high surrogates range from U+D800 to U+DBFF. 低 surrogate 範圍是從 u+dc00 到 U + dfff 範圍內的程式碼單位。The code units of low surrogates range from U+DC00 to U+DFFF. Surrogate 字組用來代表 16 的 Unicode 補充平面中的字元。Surrogate pairs are used to represent characters in the 16 Unicode supplementary planes. 下列範例會建立 surrogate 字元,並將它傳遞給Char.IsSurrogatePair(Char, Char)方法,以判斷它是否為 surrogate 字組。The following example creates a surrogate character and passes it to the Char.IsSurrogatePair(Char, Char) method to determine whether it is a surrogate pair.

    using namespace System;
    
    void main()
    {
       String^ surrogate =  L"\xD800\xDC03" ;
       for (int ctr = 0; ctr < surrogate->Length; ctr++)
          Console::Write("U+{0:X4} ", Convert::ToUInt16(surrogate[ctr]));
    
       Console::WriteLine();
       Console::WriteLine("   Is Surrogate Pair: {0}", 
                          Char::IsSurrogatePair(surrogate[0], surrogate[1]));
       Console::ReadLine();
    }
    // The example displays the following output: 
    //       U+D800 U+DC03 
    //          Is Surrogate Pair: True
    
    using System;
    
    public class Example
    {
       public static void Main()
       {
          string surrogate = "\uD800\uDC03";
          for (int ctr = 0; ctr < surrogate.Length; ctr++) 
             Console.Write("U+{0:X2} ", Convert.ToUInt16(surrogate[ctr]));
    
          Console.WriteLine();
          Console.WriteLine("   Is Surrogate Pair: {0}", 
                            Char.IsSurrogatePair(surrogate[0], surrogate[1]));
       }
    }
    // The example displays the following output:
    //       U+D800 U+DC03
    //          Is Surrogate Pair: True
    
    Module Example
       Public Sub Main()
          Dim surrogate As String = ChrW(&hD800) + ChrW(&hDC03)
          For ctr As Integer = 0 To surrogate.Length - 1
             Console.Write("U+{0:X2} ", Convert.ToUInt16(surrogate(ctr)))
          Next   
          Console.WriteLine()
          Console.WriteLine("   Is Surrogate Pair: {0}", 
                            Char.IsSurrogatePair(surrogate(0), surrogate(1)))
       End Sub
    End Module
    
    ' The example displays the following output:
    '       U+D800 U+DC03
    '          Is Surrogate Pair: True
    

字串及 Unicode 標準Strings and the Unicode Standard

字串中的字元都由 UTF 16 編碼字碼單位,這會對應到Char值。Characters in a string are represented by UTF-16 encoded code units, which correspond to Char values.

每個字元字串中的有相關聯的 Unicode 字元分類,在.NET 中所表示UnicodeCategory列舉型別。Each character in a string has an associated Unicode character category, which is represented in .NET by the UnicodeCategory enumeration. 字元或 surrogate 字組的類別目錄可決定藉由呼叫CharUnicodeInfo.GetUnicodeCategory方法。The category of a character or a surrogate pair can be determined by calling the CharUnicodeInfo.GetUnicodeCategory method.

.NET 會維護自己的字元表及其對應的分類,以確保在不同平台上執行的特定 .NET 實作,都能傳回一致的字元類別資訊。.NET maintains its own table of characters and their corresponding categories, which ensures that a specific version of a .NET implementation running on different platforms returns identical character category information. 在 Linux 及 macOS 上執行的 .NET Core,其字元分類資訊由 Unicode 的國際元件程式庫提供。On .NET Core running on Linux and macOS, character category information is provided by International Components for Unicode libraries.

下表列出 .NET 版本及其字元分類依據的 Unicode 標準版本。The following table lists .NET versions and the versions of the Unicode Standard on which their character categories are based.

.NET 版本.NET version Unicode Standard 版本Version of the Unicode Standard
.NET Framework 1.1.NET Framework 1.1 Unicode Standard 4.0.0 版The Unicode Standard, Version 4.0.0
.NET Framework 2.0.NET Framework 2.0 Unicode Standard 5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 3.5.NET Framework 3.5 Unicode Standard 5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 4.NET Framework 4 Unicode Standard 5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 4.5.NET Framework 4.5 Unicode Standard 6.3.0 版The Unicode Standard, Version 6.3.0
.NET Framework 4.51.NET Framework 4.51 Unicode Standard 6.3.0 版The Unicode Standard, Version 6.3.0
.NET Framework 4.52.NET Framework 4.52 Unicode Standard 6.3.0 版The Unicode Standard, Version 6.3.0
.NET Framework 4.6.NET Framework 4.6 Unicode Standard 6.3.0 版The Unicode Standard, Version 6.3.0
.NET Framework 4.61.NET Framework 4.61 Unicode Standard 6.3.0 版The Unicode Standard, Version 6.3.0
.NET framework 4.6.2 及更新版本.NET Framework 4.6.2 and later versions Unicode Standard 8.0.0 版The Unicode Standard, Version 8.0.0
.NET Core (所有版本).NET Core (all versions) Unicode Standard 8.0.0 版The Unicode Standard, Version 8.0.0

此外,.NET 支援字串比較和排序以 Unicode 標準為基礎。In addition, .NET supports string comparison and sorting based on the Unicode standard. 在.NET Framework 版本.NET Framework 4.NET Framework 4,.NET Framework 會維護自己的字串資料的資料表。In versions of the .NET Framework through the .NET Framework 4.NET Framework 4, the .NET Framework maintains its own table of string data. 這也是從開始的.NET Framework 的版本,則為 true.NET Framework 4.5.NET Framework 4.5在 Windows 7 上執行。This is also true of versions of the .NET Framework starting with the .NET Framework 4.5.NET Framework 4.5 running on Windows 7. 從開始.NET Framework 4.5.NET Framework 4.5執行 Windows 8 和更新版本的 Windows 作業系統上,執行階段委派字串比較和排序作業的作業系統。Starting with the .NET Framework 4.5.NET Framework 4.5 running on Window 8 and later versions of the Windows operating system, the runtime delegates string comparison and sorting operations to the operating system. 在.NET Core 上的字串比較和排序資訊係由Unicode 的國際元件程式庫。下表列出的.NET 版本和字元比較和排序所依據的 Unicode 標準版本。On .NET Core, string comparison and sorting information is provided by International Components for Unicode libraries.The following table lists the versions of .NET and the versions of the Unicode Standard on which character comparison and sorting are based.

.NET 版本.NET version Unicode Standard 版本Version of the Unicode Standard
.NET Framework 1.1.NET Framework 1.1 Unicode Standard 4.0.0 版The Unicode Standard, Version 4.0.0
.NET Framework 2.0The .NET Framework 2.0 Unicode Standard 5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 3.5.NET Framework 3.5 Unicode Standard 5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 4.NET Framework 4 Unicode Standard 5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 4.5.NET Framework 4.5 和更新版本的 Windows 7and later on Windows 7 Unicode Standard 5.0.0 版The Unicode Standard, Version 5.0.0
.NET Framework 4.5.NET Framework 4.5 和更新版本的 Windows 8 和更新版本的 Windows 作業系統上and later on Windows 8 and later Windows operating systems Unicode Standard 6.3.0 版The Unicode Standard, Version 6.3.0
.NET Core (所有版本).NET Core (all versions) 取決於基礎作業系統所支援的 Unicode Standard 版本。Depends on the version of the Unicode Standard supported by the underlying operating system.

字串和內嵌的 null 字元Strings and embedded null characters

在.NET 中,String物件可以包含內嵌的 null 字元,計算字串的長度的一部分。In .NET, a String object can include embedded null characters, which count as a part of the string's length. 不過,在某些語言如 C 和C++,null 字元表示的字串; 字串結尾它不是字串的一部分,並不會視為字串長度的一部分。However, in some languages such as C and C++, a null character indicates the end of a string; it is not considered a part of the string and is not counted as part of the string's length. 這表示下列常見的假設該 C 和C++程式設計人員或以 C 撰寫的程式庫或C++可能會使相關字串不一定有效,當套用至String物件:This means that the following common assumptions that C and C++ programmers or libraries written in C or C++ might make about strings are not necessarily valid when applied to String objects:

  • 所傳回的值strlen或是wcslen函式不一定等於String.LengthThe value returned by the strlen or wcslen functions does not necessarily equal String.Length.

  • 建立的字串strcpy_s或是wcscpy_s函式不一定等於所建立的字串String.Copy方法。The string created by the strcpy_s or wcscpy_s functions is not necessarily identical to the string created by the String.Copy method.

您應該確定該原生 C 和C++會具現化的程式碼String物件和程式碼,傳遞String物件透過平台叫用時,不假設內嵌的 null 字元標記字串結尾。You should ensure that native C and C++ code that instantiates String objects, and code that is passed String objects through platform invoke, don't assume that an embedded null character marks the end of the string.

當字串是排序 (或相較),並搜尋字串時,在字串中的內嵌的 null 字元被也視為不同。Embedded null characters in a string are also treated differently when a string is sorted (or compared) and when a string is searched. 執行區分文化特性比較兩個字串,包括使用文化特性而異的比較時,會忽略 null 字元。Null characters are ignored when performing culture-sensitive comparisons between two strings, including comparisons using the invariant culture. 將它們視為只有的序數或不區分大小寫的序數比較。They are considered only for ordinal or case-insensitive ordinal comparisons. 相反地,內嵌的 null 字元時,會永遠考慮使用方法搜尋字串,例如ContainsStartsWith,和IndexOfOn the other hand, embedded null characters are always considered when searching a string with methods such as Contains, StartsWith, and IndexOf.

字串和索引Strings and indexes

索引是位置Char中的物件 (不屬於 Unicode 字元) StringAn index is the position of a Char object (not a Unicode character) in a String. 索引是以零為起始的非負數的數字從索引位置為零的字串中的第一個位置開始。An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. 一個數字的搜尋方法,例如IndexOfLastIndexOf、 傳回字元的索引,或在字串執行個體中子字串。A number of search methods, such as IndexOf and LastIndexOf, return the index of a character or substring in the string instance.

Chars[Index]屬性可讓您存取個別Char依其在字串中的索引位置的物件。The Chars[Index] property lets you access individual Char objects by their index position in the string. 因為Chars[Index]屬性 (在 Visual Basic) 的預設屬性或索引子 (在 C# 中),您可以存取個別Char使用如下所示的程式碼字串中的物件。Because the Chars[Index] property is the default property (in Visual Basic) or the indexer (in C#), you can access the individual Char objects in a string by using code such as the following. 此程式碼會尋找泛空白字元或標點符號字元,以判斷此字串包含的幾個文字字串中。This code looks for white space or punctuation characters in a string to determine how many words the string contains.

using namespace System;

void main()
{
   String^ s1 = "This string consists of a single short sentence.";
   int nWords = 0;

   s1 = s1->Trim();      
   for (int ctr = 0; ctr < s1->Length; ctr++) {
         if (Char::IsPunctuation(s1[ctr]) | Char::IsWhiteSpace(s1[ctr]))
            nWords++;              
   }
   Console::WriteLine("The sentence\n   {0}\nhas {1} words.",
                     s1, nWords);           
}
// The example displays the following output: 
//       The sentence 
//          This string consists of a single short sentence. 
//       has 8 words.
using System;

public class Example
{
   public static void Main()
   {
      string s1 = "This string consists of a single short sentence.";
      int nWords = 0;

      s1 = s1.Trim();      
      for (int ctr = 0; ctr < s1.Length; ctr++) {
         if (Char.IsPunctuation(s1[ctr]) | Char.IsWhiteSpace(s1[ctr]))
            nWords++;              
      }
      Console.WriteLine("The sentence\n   {0}\nhas {1} words.",
                        s1, nWords);                                                                     
   }
}
// The example displays the following output:
//       The sentence
//          This string consists of a single short sentence.
//       has 8 words.
Module Example
   Public Sub Main()
      Dim s1 As String = "This string consists of a single short sentence."
      Dim nWords As Integer = 0

      s1 = s1.Trim()      
      For ctr As Integer = 0 To s1.Length - 1
         If Char.IsPunctuation(s1(ctr)) Or Char.IsWhiteSpace(s1(ctr)) 
            nWords += 1              
         End If   
      Next
      Console.WriteLine("The sentence{2}   {0}{2}has {1} words.",
                        s1, nWords, vbCrLf)                                                                     
   End Sub
End Module
' The example displays the following output:
'       The sentence
'          This string consists of a single short sentence.
'       has 8 words.

因為String類別會實作IEnumerable介面,您可以也逐一Char中所使用的字串物件foreach建構,如下列範例所示。Because the String class implements the IEnumerable interface, you can also iterate through the Char objects in a string by using a foreach construct, as the following example shows.

using namespace System;

void main()
{
   String^ s1 = "This string consists of a single short sentence.";
   int nWords = 0;

   s1 = s1->Trim();      
   for each (Char ch in s1)
   {
      if (Char::IsPunctuation(ch) | Char::IsWhiteSpace(ch))
         nWords++;              
   }
   Console::WriteLine("The sentence\n   {0}\nhas {1} words.",
                      s1, nWords);  
   Console::ReadLine();
}
// The example displays the following output: 
//       The sentence 
//          This string consists of a single short sentence. 
//       has 8 words.
using System;

public class Example
{
   public static void Main()
   {
      string s1 = "This string consists of a single short sentence.";
      int nWords = 0;

      s1 = s1.Trim();      
      foreach (var ch in s1) {
         if (Char.IsPunctuation(ch) | Char.IsWhiteSpace(ch))
            nWords++;              
      }
      Console.WriteLine("The sentence\n   {0}\nhas {1} words.",
                        s1, nWords);                                                                     
   }
}
// The example displays the following output:
//       The sentence
//          This string consists of a single short sentence.
//       has 8 words.
Module Example
   Public Sub Main()
      Dim s1 As String = "This string consists of a single short sentence."
      Dim nWords As Integer = 0

      s1 = s1.Trim()      
      For Each ch In s1
         If Char.IsPunctuation(ch) Or Char.IsWhiteSpace(ch) Then 
            nWords += 1              
         End If   
      Next
      Console.WriteLine("The sentence{2}   {0}{2}has {1} words.",
                        s1, nWords, vbCrLf)                                                                     
   End Sub
End Module
' The example displays the following output:
'       The sentence
'          This string consists of a single short sentence.
'       has 8 words.

連續的索引值可能無法對應至連續的 Unicode 字元,因為的 Unicode 字元可能是編碼為多個Char物件。Consecutive index values might not correspond to consecutive Unicode characters, because a Unicode character might be encoded as more than one Char object. 特別是,字串可能包含多字元的文字單元的基底字元後接一或多個組合的字元或 surrogate 字組所構成。In particular, a string may contain multi-character units of text that are formed by a base character followed by one or more combining characters or by surrogate pairs. 若要使用 Unicode 字元,而不是Char物件,使用System.Globalization.StringInfoTextElementEnumerator類別。To work with Unicode characters instead of Char objects, use the System.Globalization.StringInfo and TextElementEnumerator classes. 下列範例說明可搭配使用的程式碼之間的差異Char物件和與 Unicode 字元搭配運作的程式碼。The following example illustrates the difference between code that works with Char objects and code that works with Unicode characters. 它會比較字元或在每個單字的句子中的文字項目的數目。It compares the number of characters or text elements in each word of a sentence. 字串包含兩個基底字元,後面接著組合字元的序列。The string includes two sequences of a base character followed by a combining character.

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Globalization;

void main()
{
   // First sentence of The Mystery of the Yellow Room, by Leroux. 
   String^ opening = L"Ce n'est pas sans une certaine émotion que "+
                     L"je commence à raconter ici les aventures " +
                     L"extraordinaires de Joseph Rouletabille."; 
  
   // Character counters. 
   int nChars = 0;
   // Objects to store word count.
   List<int>^ chars = gcnew List<int>();
   List<int>^ elements = gcnew List<int>();

   for each (Char ch in opening) {
      // Skip the ' character. 
      if (ch == '\x0027') continue;

      if (Char::IsWhiteSpace(ch) | (Char::IsPunctuation(ch))) {
         chars->Add(nChars);
         nChars = 0;
      }
      else {
         nChars++;
      }
   }

   TextElementEnumerator^ te = StringInfo::GetTextElementEnumerator(opening);
   while (te->MoveNext()) {
      String^ s = te->GetTextElement();   
      // Skip the ' character. 
      if (s == "\x0027") continue;
      if ( String::IsNullOrEmpty(s->Trim()) | (s->Length == 1 && Char::IsPunctuation(Convert::ToChar(s)))) {
         elements->Add(nChars);         
         nChars = 0;
      }
      else {
         nChars++;
      }
   }

   // Display character counts.
   Console::WriteLine("{0,6} {1,20} {2,20}",
                      "Word #", "Char Objects", "Characters"); 
   for (int ctr = 0; ctr < chars->Count; ctr++) 
      Console::WriteLine("{0,6} {1,20} {2,20}",
                         ctr, chars[ctr], elements[ctr]); 
   Console::ReadLine();
}
// The example displays the following output:
//      Word #         Char Objects           Characters
//           0                    2                    2
//           1                    4                    4
//           2                    3                    3
//           3                    4                    4
//           4                    3                    3
//           5                    8                    8
//           6                    8                    7
//           7                    3                    3
//           8                    2                    2
//           9                    8                    8
//          10                    2                    1
//          11                    8                    8
//          12                    3                    3
//          13                    3                    3
//          14                    9                    9
//          15                   15                   15
//          16                    2                    2
//          17                    6                    6
//          18                   12                   12
using System;
using System.Collections.Generic;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      // First sentence of The Mystery of the Yellow Room, by Leroux.
      string opening = "Ce n'est pas sans une certaine émotion que "+
                       "je commence à raconter ici les aventures " +
                       "extraordinaires de Joseph Rouletabille."; 
      // Character counters.
      int nChars = 0;
      // Objects to store word count.
      List<int> chars = new List<int>();
      List<int> elements = new List<int>();
      
      foreach (var ch in opening) {
         // Skip the ' character.
         if (ch == '\u0027') continue;
              
         if (Char.IsWhiteSpace(ch) | (Char.IsPunctuation(ch))) {
            chars.Add(nChars);
            nChars = 0;
         }
         else {
            nChars++;
         }
      }

      TextElementEnumerator te = StringInfo.GetTextElementEnumerator(opening);
      while (te.MoveNext()) {
         string s = te.GetTextElement();   
         // Skip the ' character.
         if (s == "\u0027") continue;
         if ( String.IsNullOrEmpty(s.Trim()) | (s.Length == 1 && Char.IsPunctuation(Convert.ToChar(s)))) {
            elements.Add(nChars);         
            nChars = 0;
         }
         else {
            nChars++;
         }
      }

      // Display character counts.
      Console.WriteLine("{0,6} {1,20} {2,20}",
                        "Word #", "Char Objects", "Characters"); 
      for (int ctr = 0; ctr < chars.Count; ctr++) 
         Console.WriteLine("{0,6} {1,20} {2,20}",
                           ctr, chars[ctr], elements[ctr]); 
   }
}
// The example displays the following output:
//       Word #         Char Objects           Characters
//            0                    2                    2
//            1                    4                    4
//            2                    3                    3
//            3                    4                    4
//            4                    3                    3
//            5                    8                    8
//            6                    8                    7
//            7                    3                    3
//            8                    2                    2
//            9                    8                    8
//           10                    2                    1
//           11                    8                    8
//           12                    3                    3
//           13                    3                    3
//           14                    9                    9
//           15                   15                   15
//           16                    2                    2
//           17                    6                    6
//           18                   12                   12
Imports System.Collections.Generic
Imports System.Globalization

Module Example
   Public Sub Main()
      ' First sentence of The Mystery of the Yellow Room, by Leroux.
      Dim opening As String = "Ce n'est pas sans une certaine émotion que "+
                              "je commence à raconter ici les aventures " +
                              "extraordinaires de Joseph Rouletabille." 
      ' Character counters.
      Dim nChars As Integer = 0
      ' Objects to store word count.
      Dim chars As New List(Of Integer)()
      Dim elements As New List(Of Integer)()
      
      For Each ch In opening
         ' Skip the ' character.
         If ch = ChrW(&h0027) Then Continue For
              
         If Char.IsWhiteSpace(ch) Or Char.IsPunctuation(ch) Then
            chars.Add(nChars)
            nChars = 0
         Else 
            nChars += 1
         End If
      Next

      Dim te As TextElementEnumerator = StringInfo.GetTextElementEnumerator(opening)
      Do While te.MoveNext()
         Dim s As String = te.GetTextElement()   
         ' Skip the ' character.
         If s = ChrW(&h0027) Then Continue Do
         If String.IsNullOrEmpty(s.Trim()) Or (s.Length = 1 AndAlso Char.IsPunctuation(Convert.ToChar(s))) 
            elements.Add(nChars)         
            nChars = 0
         Else 
            nChars += 1
         End If
      Loop

      ' Display character counts.
      Console.WriteLine("{0,6} {1,20} {2,20}",
                        "Word #", "Char Objects", "Characters") 
      For ctr As Integer = 0 To chars.Count - 1 
         Console.WriteLine("{0,6} {1,20} {2,20}",
                           ctr, chars(ctr), elements(ctr)) 
      Next                        
   End Sub
End Module
' The example displays the following output:
'    Word #         Char Objects           Characters
'         0                    2                    2
'         1                    4                    4
'         2                    3                    3
'         3                    4                    4
'         4                    3                    3
'         5                    8                    8
'         6                    8                    7
'         7                    3                    3
'         8                    2                    2
'         9                    8                    8
'        10                    2                    1
'        11                    8                    8
'        12                    3                    3
'        13                    3                    3
'        14                    9                    9
'        15                   15                   15
'        16                    2                    2
'        17                    6                    6
'        18                   12                   12

此範例搭配使用文字項目StringInfo.GetTextElementEnumerator方法和TextElementEnumerator類別列舉字串中的所有文字項目。This example works with text elements by using the StringInfo.GetTextElementEnumerator method and the TextElementEnumerator class to enumerate all the text elements in a string. 您也可以擷取陣列,其中包含每個文字項目的起始的索引,藉由呼叫StringInfo.ParseCombiningCharacters方法。You can also retrieve an array that contains the starting index of each text element by calling the StringInfo.ParseCombiningCharacters method.

如需有關使用的文字,而不是個別的單位Char值,請參閱StringInfo類別。For more information about working with units of text rather than individual Char values, see the StringInfo class.

Null 字串和空字串Null strings and empty strings

已宣告但尚未指派值的字串是nullA string that has been declared but has not been assigned a value is null. 嘗試在該字串上呼叫方法會擲回NullReferenceExceptionAttempting to call methods on that string throws a NullReferenceException. Null 的字串是不同的空字串,也就是的字串,其值是""或String.EmptyA null string is different from an empty string, which is a string whose value is "" or String.Empty. 在某些情況下,傳遞 null 字串或空字串做為引數的方法呼叫會擲回例外狀況。In some cases, passing either a null string or an empty string as an argument in a method call throws an exception. 例如,傳遞 null 字串,以Int32.Parse方法會擲回ArgumentNullException,並傳遞空字串會擲回FormatExceptionFor example, passing a null string to the Int32.Parse method throws an ArgumentNullException, and passing an empty string throws a FormatException. 在其他情況下,方法引數可以是 null 字串或是空字串。In other cases, a method argument can be either a null string or an empty string. 例如,如果您要提供IFormattable類別的實作,您想要使用一般 ("G") 格式規範,使 null 字串和空字串。For example, if you are providing an IFormattable implementation for a class, you want to equate both a null string and an empty string with the general ("G") format specifier.

String類別包含下列兩個便利的方法可讓您測試字串是否null或空白:The String class includes the following two convenience methods that enable you to test whether a string is null or empty:

  • IsNullOrEmpty表示字串是是否null或等於String.EmptyIsNullOrEmpty, which indicates whether a string is either null or is equal to String.Empty. 這個方法就不需要使用程式碼,如下所示:This method eliminates the need to use code such as the following:

    if (str == nullptr || str->Equals(String::Empty))
    
    if (str == null || str.Equals(String.Empty))
    
    If str Is Nothing OrElse str.Equals(String.Empty) Then
    
  • IsNullOrWhiteSpace表示字串是否null,等於String.Empty,或只包含泛空白字元。IsNullOrWhiteSpace, which indicates whether a string is null, equals String.Empty, or consists exclusively of white-space characters. 這個方法就不需要使用程式碼,如下所示:This method eliminates the need to use code such as the following:

    if (str == nullptr || str->Equals(String::Empty) || str->Trim()->Equals(String::Empty))
    
    if (str == null || str.Equals(String.Empty) || str.Trim().Equals(String.Empty))
    
    If str Is Nothing OrElse str.Equals(String.Empty) OrElse str.Trim().Equals(String.Empty)
    

下列範例會使用IsNullOrEmpty方法中的IFormattable.ToString的自訂實作Temperature類別。The following example uses the IsNullOrEmpty method in the IFormattable.ToString implementation of a custom Temperature class. 方法支援的"G","C"、"F"、"K"格式字串。The method supports the "G", "C", "F", and "K" format strings. 如果是空白的格式字串或格式字串的值是null傳遞至此方法,其值變更為"G"格式字串。If an empty format string or a format string whose value is null is passed to the method, its value is changed to the "G" format string.

public:
   virtual String^ ToString(String^ format, IFormatProvider^ provider) 
   {
      if (String::IsNullOrEmpty(format)) format = "G";  
      if (provider == nullptr) provider = CultureInfo::CurrentCulture;
      
      switch (Convert::ToUInt16(format->ToUpperInvariant()))
      {
         // Return degrees in Celsius.    
         case 'G':
         case 'C':
            return temp.ToString("F2", provider) + L"�C";
         // Return degrees in Fahrenheit.
         case 'F': 
            return (temp * 9 / 5 + 32).ToString("F2", provider) + L"�F";
         // Return degrees in Kelvin.
         case 'K':   
            return (temp + 273.15).ToString();
         default:
            throw gcnew FormatException(
                  String::Format("The {0} format string is not supported.", 
                                 format));
      }                                   
   }
public string ToString(string format, IFormatProvider provider) 
{
   if (String.IsNullOrEmpty(format)) format = "G";  
   if (provider == null) provider = CultureInfo.CurrentCulture;
   
   switch (format.ToUpperInvariant())
   {
      // Return degrees in Celsius.    
      case "G":
      case "C":
         return temp.ToString("F2", provider) + "°C";
      // Return degrees in Fahrenheit.
      case "F": 
         return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F";
      // Return degrees in Kelvin.
      case "K":   
         return (temp + 273.15).ToString();
      default:
         throw new FormatException(
               String.Format("The {0} format string is not supported.", 
                             format));
   }                                   
}
Public Overloads Function ToString(fmt As String, provider As IFormatProvider) As String _
                Implements IFormattable.ToString
   If String.IsNullOrEmpty(fmt) Then fmt = "G"  
   If provider Is Nothing Then provider = CultureInfo.CurrentCulture
   
   Select Case fmt.ToUpperInvariant()
      ' Return degrees in Celsius.    
      Case "G", "C"
         Return temp.ToString("F2", provider) + "°C"
      ' Return degrees in Fahrenheit.
      Case "F" 
         Return (temp * 9 / 5 + 32).ToString("F2", provider) + "°F"
      ' Return degrees in Kelvin.
      Case "K"   
         Return (temp + 273.15).ToString()
      Case Else
         Throw New FormatException(
               String.Format("The {0} format string is not supported.", 
                             fmt))
    End Select                                   
End Function

不變性和 StringBuilder 類別Immutability and the StringBuilder class

AString物件稱為不可變 (唯讀),因為一旦建立後便無法修改其值。A String object is called immutable (read-only), because its value cannot be modified after it has been created. 若要修改顯示的方法String物件實際上會傳回新String包含修改的物件。Methods that appear to modify a String object actually return a new String object that contains the modification.

字串是不可變的因為執行的字串操作常式重複新增或刪除項目似乎是單一字串可以精確顯著的效能負面影響。Because strings are immutable, string manipulation routines that perform repeated additions or deletions to what appears to be a single string can exact a significant performance penalty. 例如,下列程式碼會使用亂數產生器建立具有在範圍內以 0x052F 0x0001 1000 個字元的字串。For example, the following code uses a random number generator to create a string with 1000 characters in the range 0x0001 to 0x052F. 雖然程式碼會使用字串串連來將新的字元附加至現有的字串,名為str,它實際上會建立新String針對每個串連作業的物件。Although the code appears to use string concatenation to append a new character to the existing string named str, it actually creates a new String object for each concatenation operation.

using namespace System;
using namespace System::IO;
using namespace System::Text;

void main()
{
   Random^ rnd = gcnew Random();

   String^ str = String::Empty;
   StreamWriter^ sw = gcnew StreamWriter(".\\StringFile.txt", 
                        false, Encoding::Unicode);

   for (int ctr = 0; ctr <= 1000; ctr++) {
      str += Convert::ToChar(rnd->Next(1, 0x0530)); 
      if (str->Length % 60 == 0)
         str += Environment::NewLine;          
   }                    
   sw->Write(str);
   sw->Close();
}
using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      
      string str = String.Empty;
      StreamWriter sw = new StreamWriter(@".\StringFile.txt", 
                           false, Encoding.Unicode);

      for (int ctr = 0; ctr <= 1000; ctr++) {
         str += Convert.ToChar(rnd.Next(1, 0x0530)); 
         if (str.Length % 60 == 0)
            str += Environment.NewLine;          
      }                    
      sw.Write(str);
      sw.Close();
   }
}
Imports System.IO
Imports System.Text

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      
      Dim str As String = String.Empty
      Dim sw As New StreamWriter(".\StringFile.txt", 
                           False, Encoding.Unicode)

      For ctr As Integer = 0 To 1000
         str += ChrW(rnd.Next(1, &h0530)) 
         If str.Length Mod 60 = 0 Then str += vbCrLf          
      Next                    
      sw.Write(str)
      sw.Close()
   End Sub
End Module

您可以使用StringBuilder類別而不是String作業的字串值的多個變更的類別。You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string. 不同的執行個體String類別,StringBuilder是可變動的物件; 當您串連、 附加或刪除從字串的子字串時,作業將會在單一字串。Unlike instances of the String class, StringBuilder objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. 當您完成修改的值StringBuilder物件,您可以呼叫其StringBuilder.ToString方法將它轉換成字串。When you have finished modifying the value of a StringBuilder object, you can call its StringBuilder.ToString method to convert it to a string. 下列範例會取代String在上述範例中用來串連來使用 0x052F 0x0001 之範圍中的 1000 個隨機字元StringBuilder物件。The following example replaces the String used in the previous example to concatenate 1000 random characters in the range to 0x0001 to 0x052F with a StringBuilder object.

using namespace System;
using namespace System::IO;
using namespace System::Text;

void main()
{
   Random^ rnd = gcnew Random();

   StringBuilder^ sb = gcnew StringBuilder();
   StreamWriter^ sw = gcnew StreamWriter(".\\StringFile.txt", 
                        false, Encoding::Unicode);

   for (int ctr = 0; ctr <= 1000; ctr++) {
      sb->Append(Convert::ToChar(rnd->Next(1, 0x0530))); 
      if (sb->Length % 60 == 0)
         sb->AppendLine();          
   }                    
   sw->Write(sb->ToString());
   sw->Close();
}
using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      StringBuilder sb = new StringBuilder();
      StreamWriter sw = new StreamWriter(@".\StringFile.txt", 
                                         false, Encoding.Unicode);

      for (int ctr = 0; ctr <= 1000; ctr++) {
         sb.Append(Convert.ToChar(rnd.Next(1, 0x0530))); 
         if (sb.Length % 60 == 0)
            sb.AppendLine();          
      }                    
      sw.Write(sb.ToString());
      sw.Close();
   }
}
Imports System.IO
Imports System.Text

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim sb As New StringBuilder()
      Dim sw As New StreamWriter(".\StringFile.txt", 
                                 False, Encoding.Unicode)

      For ctr As Integer = 0 To 1000
         sb.Append(ChrW(rnd.Next(1, &h0530))) 
         If sb.Length Mod 60 = 0 Then sb.AppendLine()          
      Next                    
      sw.Write(sb.ToString())
      sw.Close()
   End Sub
End Module

序數與文化特性的作業Ordinal vs. culture-sensitive operations

成員String類別上執行序數或區分文化特性 (語言) 作業String物件。Members of the String class perform either ordinal or culture-sensitive (linguistic) operations on a String object. 序數的作業會在每個數值上Char物件。An ordinal operation acts on the numeric value of each Char object. 區分文化特性的作業處理程式碼的值String物件,並採用特定文化特性的大小寫、 排序、 格式化和剖析規則列入考量。A culture-sensitive operation acts on the value of the String object, and takes culture-specific casing, sorting, formatting, and parsing rules into account. 明確宣告的文化特性或目前的文化特性隱含的內容中,執行區分文化特性的作業。Culture-sensitive operations execute in the context of an explicitly declared culture or the implicit current culture. 它們會對相同的字串時,兩種作業可能會產生非常不同的結果。The two kinds of operations can produce very different results when they are performed on the same string.

.NET 也支援不區分文化特性的語言字串作業,使用文化特性而異 (CultureInfo.InvariantCulture),以鬆散基礎區域的獨立的英文文化特性設定。.NET also supports culture-insensitive linguistic string operations by using the invariant culture (CultureInfo.InvariantCulture), which is loosely based on the culture settings of the English language independent of region. 不同於其他System.Globalization.CultureInfo保證維持一致的單一電腦上,從系統中,而橫跨的.NET 版本的系統設定、 不區分文化特性設定。Unlike other System.Globalization.CultureInfo settings, the settings of the invariant culture are guaranteed to remain consistent on a single computer, from system to system, and across versions of .NET. 跨所有文化特性可以看到視為一種黑色方塊,以確保穩定性的字串比較和排序文化特性而異。The invariant culture can be seen as a kind of black box that ensures stability of string comparisons and ordering across all cultures.

重要

如果您的應用程式可讓安全性決策的相關符號的識別碼,例如檔案名稱或具名管道,或需保存的資料,例如 XML 檔案中以文字為基礎的資料,作業應該使用序數比較,而不是區分文化特性的比較。If your application makes a security decision about a symbolic identifier such as a file name or named pipe, or about persisted data such as the text-based data in an XML file, the operation should use an ordinal comparison instead of a culture-sensitive comparison. 這是因為區分文化特性的比較可以作用中,產生不同的結果,根據文化特性而序數比較取決於比較字元的二進位值。This is because a culture-sensitive comparison can yield different results depending on the culture in effect, whereas an ordinal comparison depends solely on the binary value of the compared characters.

重要

執行字串作業的大部分方法包括具有類型參數的多載StringComparison,這可讓您指定方法是否執行序數或區分文化特性的作業。Most methods that perform string operations include an overload that has a parameter of type StringComparison, which enables you to specify whether the method performs an ordinal or culture-sensitive operation. 一般情況下,您應該呼叫這個多載來進行的意圖,在方法呼叫清除。In general, you should call this overload to make the intent of your method call clear. 最佳做法及使用序數和區分文化特性字串作業的指引,請參閱使用字串的最佳做法For best practices and guidance for using ordinal and culture-sensitive operations on strings, see Best Practices for Using Strings.

作業大小寫剖析和格式化比較和排序,以及測試是否相等可以是序數或區分文化特性。Operations for casing, parsing and formatting, comparison and sorting, and testing for equality can be either ordinal or culture-sensitive. 下列各節將討論每個類別的作業。The following sections discuss each category of operation.

提示

您應該一律呼叫方法多載,可讓您的方法呼叫清除目的。You should always call a method overload that makes the intent of your method call clear. 比方說,而不是呼叫Compare(String, String)方法以執行區分文化特性比較兩個字串的使用目前的文化特性的慣例,您應該呼叫Compare(String, String, StringComparison)方法,其值為StringComparison.CurrentCulturecomparisonType引數。For example, instead of calling the Compare(String, String) method to perform a culture-sensitive comparison of two strings by using the conventions of the current culture, you should call the Compare(String, String, StringComparison) method with a value of StringComparison.CurrentCulture for the comparisonType argument. 如需詳細資訊,請參閱使用字串的最佳做法For more information, see Best Practices for Using Strings.

您可以下載排序權數資料表,該文字檔集合包含在 Windows 作業系統排序及比較作業中使用的字元權數資訊,以及下載預設 Unicode 定序元素資料表 (適用於 Linux 和 macOS 的排序權數資料表)。You can download the Sorting Weight Tables, a set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, and the Default Unicode Collation Element Table, the sort weight table for Linux and macOS.

大小寫Casing

大小寫規則會決定如何變更大小寫的 Unicode 字元;例如,從小寫為大寫。Casing rules determine how to change the capitalization of a Unicode character; for example, from lowercase to uppercase. 通常,會執行大小寫作業之前的字串比較。Often, a casing operation is performed before a string comparison. 例如,字串可能會轉換為大寫,以便與另一個大寫的字串。For example, a string might be converted to uppercase so that it can be compared with another uppercase string. 您可以將轉換為小寫藉由呼叫字串中的字元ToLower或是ToLowerInvariant方法,而且您可以將它們轉換成大寫,藉由呼叫ToUpperToUpperInvariant方法。You can convert the characters in a string to lowercase by calling the ToLower or ToLowerInvariant method, and you can convert them to uppercase by calling the ToUpper or ToUpperInvariant method. 此外,您可以使用TextInfo.ToTitleCase方法將字串轉換為字首大寫。In addition, you can use the TextInfo.ToTitleCase method to convert a string to title case.

注意

.NET Core 僅在 Linux 和 macOS 系統上執行: C 和 Posix 文化特性的定序行為一律區分大小寫,因為這些文化特性不會使用預期的 Unicode 定序順序。.NET Core running on Linux and macOS systems only: The collation behavior for the C and Posix cultures is always case-sensitive because these cultures do not use the expected Unicode collation order. 建議您使用 C 或 Posix 以外的文化特性來執行區分文化特性、不區分大小寫的排序作業。We recommend that you use a culture other than C or Posix for performing culture-sensitive, case-insensitive sorting operations.

大小寫的作業可以根據目前文化特性、 指定的文化特性或文化特性而異的規則。Casing operations can be based on the rules of the current culture, a specified culture, or the invariant culture. 大小寫對應使用的文化特性而異,因為大小寫作業的結果可以異的文化特性。Because case mappings can vary depending on the culture used, the result of casing operations can vary based on culture. 有三種大小寫的實際差異:The actual differences in casing are of three kinds:

  • 在 大小寫的 LATIN CAPITAL LETTER I 對應的差異 (u+0049),拉丁小型字母 I (u+0069),LATIN CAPITAL LETTER I (u+0130),上述的點和拉丁文小型字母無點 」 (U + 0131)。Differences in the case mapping of LATIN CAPITAL LETTER I (U+0049), LATIN SMALL LETTER I (U+0069), LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130), and LATIN SMALL LETTER DOTLESS I (U+0131). TR-TR (土耳其文 (土耳其)) 和 az-Latn-AZ (亞塞拜然,拉丁) 文化特性,在和中的 tr、 az 和 az Latn 中性文化特性,LATIN CAPITAL LETTER I 的對等小寫; 拉丁文小型字母無點 1,而拉丁文小型字母 I 的大寫對應項拉丁大寫字母我使用上述的點。In the tr-TR (Turkish (Turkey)) and az-Latn-AZ (Azerbaijan, Latin) cultures, and in the tr, az, and az-Latn neutral cultures, the lowercase equivalent of LATIN CAPITAL LETTER I is LATIN SMALL LETTER DOTLESS I, and the uppercase equivalent of LATIN SMALL LETTER I is LATIN CAPITAL LETTER I WITH DOT ABOVE. 在所有其他的文化特性,包括文化特性而異,拉丁小型字母 I 與 LATIN CAPITAL LETTER 我是小寫和大寫對等項目。In all other cultures, including the invariant culture, LATIN SMALL LETTER I and LATIN CAPITAL LETTER I are lowercase and uppercase equivalents.

    下列範例示範如何設計的字串比較,以避免檔案系統存取權可能會失敗它依賴區分文化特性的大小寫比較。The following example demonstrates how a string comparison designed to prevent file system access can fail if it relies on a culture-sensitive casing comparison. (不區分文化特性的大小寫慣例應該已使用。)(The casing conventions of the invariant culture should have been used.)

    using System;
    using System.Globalization;
    using System.Threading;
    
    public class Example
    {
       const string disallowed = "file";
       
       public static void Main()
       {
          IsAccessAllowed(@"FILE:\\\c:\users\user001\documents\FinancialInfo.txt");
       }
    
       private static void IsAccessAllowed(String resource)
       {
          CultureInfo[] cultures = { CultureInfo.CreateSpecificCulture("en-US"),
                                     CultureInfo.CreateSpecificCulture("tr-TR") };
          String scheme = null;
          int index = resource.IndexOfAny( new Char[] { '\\', '/' } );
          if (index > 0) 
             scheme = resource.Substring(0, index - 1);
    
          // Change the current culture and perform the comparison.
          foreach (var culture in cultures) {
             Thread.CurrentThread.CurrentCulture = culture;
             Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
             Console.WriteLine(resource);
             Console.WriteLine("Access allowed: {0}", 
                               ! String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase));      
             Console.WriteLine();
          }   
       }
    }
    // The example displays the following output:
    //       Culture: English (United States)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: False
    //       
    //       Culture: Turkish (Turkey)
    //       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    //       Access allowed: True
    
    Imports System.Globalization
    Imports System.Threading
    
    Module Example
       Const disallowed = "file"
       
       Public Sub Main()
          IsAccessAllowed("FILE:\\\c:\users\user001\documents\FinancialInfo.txt")
       End Sub
    
       Private Sub IsAccessAllowed(resource As String)
          Dim cultures() As CultureInfo = { CultureInfo.CreateSpecificCulture("en-US"),
                                            CultureInfo.CreateSpecificCulture("tr-TR") }
          Dim scheme As String = Nothing
          Dim index As Integer = resource.IndexOfAny( {"\"c, "/"c })
          If index > 0 Then scheme = resource.Substring(0, index - 1)
    
          ' Change the current culture and perform the comparison.
          For Each culture In cultures
             Thread.CurrentThread.CurrentCulture = culture
             Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName)
             Console.WriteLine(resource)
             Console.WriteLine("Access allowed: {0}", 
                               Not String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase))      
             Console.WriteLine()
          Next   
       End Sub      
    End Module
    ' The example displays the following output:
    '       Culture: English (United States)
    '       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    '       Access allowed: False
    '       
    '       Culture: Turkish (Turkey)
    '       FILE:\\\c:\users\user001\documents\FinancialInfo.txt
    '       Access allowed: True
    
  • 在 大小寫對應而異的文化特性和所有其他文化特性之間的差異。Differences in case mappings between the invariant culture and all other cultures. 在這些情況下,使用文化特性而異的大小寫規則變更為大寫或小寫字元,將會傳回相同的字元。In these cases, using the casing rules of the invariant culture to change a character to uppercase or lowercase returns the same character. 對於所有其他的文化特性,它會傳回不同的字元。For all other cultures, it returns a different character. 某些受影響的字元都是以下列的表所述。Some of the affected characters are listed in the following table.

    字元Character 如果變更為If changed to ReturnsReturns
    MICRON 登 (U + 00B5)MICRON SIGN (U+00B5) 大寫Uppercase 希臘文大寫字母 MU (U +-39 C)GREEK CAPITAL LETTER MU (U+-39C)
    LATIN CAPITAL LETTER 我加上點上方 (U+0130)LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130) 小寫Lowercase 拉丁文小型字母 I (U+0069)LATIN SMALL LETTER I (U+0069)
    拉丁文小寫字母無點我 (U + 0131)LATIN SMALL LETTER DOTLESS I (U+0131) 大寫Uppercase 拉丁大寫字母 I (U+0049)LATIN CAPITAL LETTER I (U+0049)
    拉丁文小寫字母長 S (U + 017F)LATIN SMALL LETTER LONG S (U+017F) 大寫Uppercase LATIN CAPITAL LETTER S (U + 0053)LATIN CAPITAL LETTER S (U+0053)
    有勾的小寫字母 Z 的拉丁大寫字母 D (U + 01C 5)LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON (U+01C5) 小寫Lowercase 有勾的拉丁小寫字母 DZ (U + 01C 6)LATIN SMALL LETTER DZ WITH CARON (U+01C6)
    結合希臘 YPOGEGRAMMENI (U + 0345)COMBINING GREEK YPOGEGRAMMENI (U+0345) 大寫Uppercase 希臘文大寫字母 IOTA (U + 0399)GREEK CAPITAL LETTER IOTA (U+0399)
  • ASCII 字元範圍中的兩個字母混合大小寫組的大小寫對應的差異。Differences in case mappings of two-letter mixed-case pairs in the ASCII character range. 在大部分文化中,兩個字母混合大小寫組等於的對等的兩個字母大寫或小寫組。In most cultures, a two-letter mixed-case pair is equal to the equivalent two-letter uppercase or lowercase pair. 這不適用於下列兩個字母組中的下列的文化特性,因為在每個案例中,它們會比較到雙拼詞:This is not true for the following two-letter pairs in the following cultures, because in each case they are compared to a digraph:

    • 「 lJ"和"nJ"HR-HR (克羅埃西亞文 (克羅埃西亞)) 文化特性中。"lJ" and "nJ" in the hr-HR (Croatian (Croatia)) culture.

    • 「 cH"CS-CZ (捷克文 (捷克共和國)) 和 sk-SK (斯洛伐克文 (斯洛伐克)) 文化特性。"cH" in the cs-CZ (Czech (Czech Republic)) and sk-SK (Slovak (Slovakia)) cultures.

    • "aA"DA-DK (丹麥文 (丹麥)) 文化特性中。"aA" in the da-DK (Danish (Denmark)) culture.

    • "cS"、"dZ"、"dZS"、"nY"、"sZ"、"tY,"和"zs"表示 HU-HU (匈牙利文 (匈牙利)) 文化特性中。"cS", "dZ", "dZS", "nY", "sZ", "tY", and "zS" in the hu-HU (Hungarian (Hungary)) culture.

    • 「 cH"和"lL"es ES_tradnl (西班牙文 (西班牙,傳統排序)) 文化特性中。"cH" and "lL" in the es-ES_tradnl (Spanish (Spain, Traditional Sort)) culture.

    • 「 cH"、"gI"、"kH"、"nG""nH"、"pH","qU',"tH",並在 vi VN (越南文 (越南)) 文化特性中的"tR"。"cH", "gI", "kH", "nG" "nH", "pH", "qU', "tH", and "tR" in the vi-VN (Vietnamese (Vietnam)) culture.

    不過,很少會遇到這些字組的區分文化特性的比較會建立問題的情況下,因為這些組並不常見的固定的字串或識別項。However, it is unusual to encounter a situation in which a culture-sensitive comparison of these pairs creates problems, because these pairs are uncommon in fixed strings or identifiers.

下列範例會說明一些在大小寫規則時將字串轉換成大寫的文化特性之間的差異。The following example illustrates some of the differences in casing rules between cultures when converting strings to uppercase.

using namespace System;
using namespace System::Globalization;
using namespace System::IO;

String^ ShowHexValue(String^ s);

void main()
{
   StreamWriter^ sw = gcnew StreamWriter(".\\case.txt");   
   array<String^>^ words = gcnew array<String^> { L"file", L"sıfır", L"Dženana" };
   array<CultureInfo^>^ cultures = gcnew array<CultureInfo^> { CultureInfo::InvariantCulture, 
                                                               gcnew CultureInfo("en-US"),  
                                                               gcnew CultureInfo("tr-TR") };

   for each (String^ word in words) {
      sw->WriteLine("{0}:", word);
      for each (CultureInfo^ culture in cultures) {
         String^ name = String::IsNullOrEmpty(culture->Name) ? 
                              "Invariant" : culture->Name;
         String^ upperWord = word->ToUpper(culture);
         sw->WriteLine("   {0,10}: {1,7} {2, 38}", name, 
                        upperWord, ShowHexValue(upperWord));

      }
      sw->WriteLine();  
   }
   sw->Close();
}

String^ ShowHexValue(String^ s)
{
   String^ retval = nullptr;
   for each (Char ch in s) {
      array<Byte>^ bytes = BitConverter::GetBytes(ch);
      retval += String::Format("{0:X2} {1:X2} ", bytes[1], bytes[0]);     
   }
   return retval;
} 
// The example displays the following output: 
//    file: 
//        Invariant:    FILE               00 46 00 49 00 4C 00 45  
//            en-US:    FILE               00 46 00 49 00 4C 00 45  
//            tr-TR:    FİLE               00 46 01 30 00 4C 00 45  
//     
//    sıfır: 
//        Invariant:   SıFıR         00 53 01 31 00 46 01 31 00 52  
//            en-US:   SIFIR         00 53 00 49 00 46 00 49 00 52  
//            tr-TR:   SIFIR         00 53 00 49 00 46 00 49 00 52  
//     
//    Dženana: 
//        Invariant:  DžENANA   01 C5 00 45 00 4E 00 41 00 4E 00 41  
//            en-US:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41  
//            tr-TR:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41 
using System;
using System.Globalization;
using System.IO;

public class Example
{
   public static void Main()
   {
      StreamWriter sw = new StreamWriter(@".\case.txt");   
      string[] words = { "file", "sıfır", "Dženana" };
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 new CultureInfo("en-US"),  
                                 new CultureInfo("tr-TR") };

      foreach (var word in words) {
         sw.WriteLine("{0}:", word);
         foreach (var culture in cultures) {
            string name = String.IsNullOrEmpty(culture.Name) ? 
                                 "Invariant" : culture.Name;
            string upperWord = word.ToUpper(culture);
            sw.WriteLine("   {0,10}: {1,7} {2, 38}", name, 
                         upperWord, ShowHexValue(upperWord));
     
         }
         sw.WriteLine();  
      }
      sw.Close();
   }

   private static string ShowHexValue(string s)
   {
      string retval = null;
      foreach (var ch in s) {
         byte[] bytes = BitConverter.GetBytes(ch);
         retval += String.Format("{0:X2} {1:X2} ", bytes[1], bytes[0]);     
      }
      return retval;
   } 
}
// The example displays the following output:
//    file:
//        Invariant:    FILE               00 46 00 49 00 4C 00 45 
//            en-US:    FILE               00 46 00 49 00 4C 00 45 
//            tr-TR:    FİLE               00 46 01 30 00 4C 00 45 
//    
//    sıfır:
//        Invariant:   SıFıR         00 53 01 31 00 46 01 31 00 52 
//            en-US:   SIFIR         00 53 00 49 00 46 00 49 00 52 
//            tr-TR:   SIFIR         00 53 00 49 00 46 00 49 00 52 
//    
//    Dženana:
//        Invariant:  DžENANA   01 C5 00 45 00 4E 00 41 00 4E 00 41 
//            en-US:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41 
//            tr-TR:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41 
Imports System.Globalization
Imports System.IO

Module Example
   Public Sub Main()
      Dim sw As New StreamWriter(".\case.txt")   
      Dim words As String() = { "file", "sıfır", "Dženana" }
      Dim cultures() As CultureInfo = { CultureInfo.InvariantCulture, 
                                        New CultureInfo("en-US"),  
                                        New CultureInfo("tr-TR") }

      For Each word In words
         sw.WriteLine("{0}:", word)
         For Each culture In cultures
            Dim name As String = If(String.IsNullOrEmpty(culture.Name),  
                                 "Invariant", culture.Name)
            Dim upperWord As String = word.ToUpper(culture)
            sw.WriteLine("   {0,10}: {1,7} {2, 38}", name, 
                         upperWord, ShowHexValue(upperWord))
     
         Next
         sw.WriteLine()  
      Next
      sw.Close()
   End Sub

   Private Function ShowHexValue(s As String) As String
      Dim retval As String = Nothing
      For Each ch In s
         Dim bytes() As Byte = BitConverter.GetBytes(ch)
         retval += String.Format("{0:X2} {1:X2} ", bytes(1), bytes(0))     
      Next
      Return retval
   End Function
End Module
' The example displays the following output:
'    file:
'        Invariant:    FILE               00 46 00 49 00 4C 00 45 
'            en-US:    FILE               00 46 00 49 00 4C 00 45 
'            tr-TR:    FİLE               00 46 01 30 00 4C 00 45 
'    
'    sıfır:
'        Invariant:   SıFıR         00 53 01 31 00 46 01 31 00 52 
'            en-US:   SIFIR         00 53 00 49 00 46 00 49 00 52 
'            tr-TR:   SIFIR         00 53 00 49 00 46 00 49 00 52 
'    
'    Dženana:
'        Invariant:  DžENANA   01 C5 00 45 00 4E 00 41 00 4E 00 41 
'            en-US:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41 
'            tr-TR:  DŽENANA   01 C4 00 45 00 4E 00 41 00 4E 00 41  

剖析和格式化Parsing and formatting

格式化和剖析是反向作業。Formatting and parsing are inverse operations. 格式化規則決定的值,例如日期和時間或數字,轉換成其字串表示法,而剖析規則會決定如何將轉換為值,例如日期和時間的字串表示。Formatting rules determine how to convert a value, such as a date and time or a number, to its string representation, whereas parsing rules determine how to convert a string representation to a value such as a date and time. 格式化和剖析規則均依存於文化特性的慣例。Both formatting and parsing rules are dependent on cultural conventions. 下列範例說明在解譯的特定文化特性的日期字串時,可能會發生模稜兩可。The following example illustrates the ambiguity that can arise when interpreting a culture-specific date string. 而不需要知道用來產生日期字串的文化特性的慣例,不可能知道 03/01/2011年,3/1/2011,01/03/2011年代表 2011 年 1 月 3 日或 2011 年 3 月 1 日。Without knowing the conventions of the culture that was used to produce a date string, it is not possible to know whether 03/01/2011, 3/1/2011, and 01/03/2011 represent January 3, 2011 or March 1, 2011.

using namespace System;
using namespace System::Globalization;

void main()
{
   DateTime^ date = gcnew DateTime(2011, 3, 1);
   array<CultureInfo^>^ cultures = gcnew array<CultureInfo^> { CultureInfo::InvariantCulture, 
                                                               gcnew CultureInfo("en-US"), 
                                                               gcnew CultureInfo("fr-FR") };

   for each (CultureInfo^ culture in cultures)
      Console::WriteLine("{0,-12} {1}", String::IsNullOrEmpty(culture->Name) ?
                        "Invariant" : culture->Name, 
                        date->ToString("d", culture));                                    
}
// The example displays the following output: 
//       Invariant    03/01/2011 
//       en-US        3/1/2011 
//       fr-FR        01/03/2011
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime date = new DateTime(2011, 3, 1);
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 new CultureInfo("en-US"), 
                                 new CultureInfo("fr-FR") };

      foreach (var culture in cultures)
         Console.WriteLine("{0,-12} {1}", String.IsNullOrEmpty(culture.Name) ?
                           "Invariant" : culture.Name, 
                           date.ToString("d", culture));                                    
   }
}
// The example displays the following output:
//       Invariant    03/01/2011
//       en-US        3/1/2011
//       fr-FR        01/03/2011
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dat As Date = #3/1/2011#
      Dim cultures() As CultureInfo = { CultureInfo.InvariantCulture, 
                                        New CultureInfo("en-US"), 
                                        New CultureInfo("fr-FR") }

      For Each culture In cultures
         Console.WriteLine("{0,-12} {1}", If(String.IsNullOrEmpty(culture.Name), 
                           "Invariant", culture.Name), 
                           dat.ToString("d", culture))
      Next                                                         
   End Sub
End Module
' The example displays the following output:
'       Invariant    03/01/2011
'       en-US        3/1/2011
'       fr-FR        01/03/2011

同樣地,如下列範例所示,單一字串可能會產生不同的日期,根據文化特性的慣例用於剖析作業。Similarly, as the following example shows, a single string can produce different dates depending on the culture whose conventions are used in the parsing operation.

using namespace System;
using namespace System::Globalization;

void main()
{
   String^ dateString = "07/10/2011";
   array<CultureInfo^>^ cultures = gcnew array<CultureInfo^> { CultureInfo::InvariantCulture, 
                                                               CultureInfo::CreateSpecificCulture("en-GB"), 
                                                               CultureInfo::CreateSpecificCulture("en-US") };
   Console::WriteLine("{0,-12} {1,10} {2,8} {3,8}\n", "Date String", "Culture", 
                                                "Month", "Day");
   for each (CultureInfo^ culture in cultures) {
      DateTime date = DateTime::Parse(dateString, culture);
      Console::WriteLine("{0,-12} {1,10} {2,8} {3,8}", dateString, 
                        String::IsNullOrEmpty(culture->Name) ?
                        "Invariant" : culture->Name, 
                        date.Month, date.Day);
   }                      
}
// The example displays the following output: 
//       Date String     Culture    Month      Day 
//        
//       07/10/2011    Invariant        7       10 
//       07/10/2011        en-GB       10        7 
//       07/10/2011        en-US        7       10

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string dateString = "07/10/2011";
      CultureInfo[] cultures = { CultureInfo.InvariantCulture, 
                                 CultureInfo.CreateSpecificCulture("en-GB"), 
                                 CultureInfo.CreateSpecificCulture("en-US") };
      Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}\n", "Date String", "Culture", 
                                                 "Month", "Day");
      foreach (var culture in cultures) {
         DateTime date = DateTime.Parse(dateString, culture);
         Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", dateString, 
                           String.IsNullOrEmpty(culture.Name) ?
                           "Invariant" : culture.Name, 
                           date.Month, date.Day);
      }                      
   }
}
// The example displays the following output:
//       Date String     Culture    Month      Day
//       
//       07/10/2011    Invariant        7       10
//       07/10/2011        en-GB       10        7
//       07/10/2011        en-US        7       10
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateString As String = "07/10/2011"
      Dim cultures() As CultureInfo = { CultureInfo.InvariantCulture, 
                                        CultureInfo.CreateSpecificCulture("en-GB"), 
                                        CultureInfo.CreateSpecificCulture("en-US") }
      Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", "Date String", "Culture", 
                                                 "Month", "Day")
      Console.WriteLine()                                                 
      For Each culture In cultures
         Dim dat As Date = DateTime.Parse(dateString, culture)
         Console.WriteLine("{0,-12} {1,10} {2,8} {3,8}", dateString, 
                           If(String.IsNullOrEmpty(culture.Name), 
                           "Invariant", culture.Name), 
                           dat.Month, dat.Day)
      Next
   End Sub
End Module
' The example displays the following output:
'       Date String     Culture    Month      Day
'       
'       07/10/2011    Invariant        7       10
'       07/10/2011        en-GB       10        7
'       07/10/2011        en-US        7       10

字串比較和排序String comparison and sorting

比較和排序字串的慣例而異的文化。Conventions for comparing and sorting strings vary from culture to culture. 例如,排序次序可能會根據語音 或字元的視覺表示法。For example, the sort order may be based on phonetics or on the visual representation of characters. 在東亞語言中,字元是依照筆劃和表意字元的巨大。In East Asian languages, characters are sorted by the stroke and radical of ideographs. 排序也取決於順序語言和文化特性使用的字母。Sorting also depends on the order languages and cultures use for the alphabet. 例如,丹麥文的 "Æ" 字元在字母順序中排列在 "Z" 之後。For example, the Danish language has an "Æ" character that it sorts after "Z" in the alphabet. 此外,比較可以是區分大小寫或區分大小寫,而且在某些情況下的大小寫規則也因文化特性。In addition, comparisons can be case-sensitive or case-insensitive, and in some cases casing rules also differ by culture. 序數比較,相反地,會使用字串時比較和排序字串中的個別字元的 Unicode 字碼指標。Ordinal comparison, on the other hand, uses the Unicode code points of individual characters in a string when comparing and sorting strings.

排序規則決定彼此的 Unicode 字元的字母順序和兩個字串比較。Sort rules determine the alphabetic order of Unicode characters and how two strings compare to each other. 例如,String.Compare(String, String, StringComparison)方法會比較兩個字串,根據StringComparison參數。For example, the String.Compare(String, String, StringComparison) method compares two strings based on the StringComparison parameter. 如果參數值StringComparison.CurrentCulture,如果參數值,這個方法會執行語言比較,會使用目前的文化特性; 慣例StringComparison.Ordinal,此方法會執行序數比較。If the parameter value is StringComparison.CurrentCulture, the method performs a linguistic comparison that uses the conventions of the current culture; if the parameter value is StringComparison.Ordinal, the method performs an ordinal comparison. 因此,如下列範例所示,如果目前的文化特性是美國英文、 第一次呼叫String.Compare(String, String, StringComparison)(使用區分文化特性的比較) 的方法會考慮"a"小於"A",但相同的方法 (使用序數比較) 的第二個呼叫會考慮"a"大於"A"。Consequently, as the following example shows, if the current culture is U.S. English, the first call to the String.Compare(String, String, StringComparison) method (using culture-sensitive comparison) considers "a" less than "A", but the second call to the same method (using ordinal comparison) considers "a" greater than "A".

using namespace System;
using namespace System::Globalization;
using namespace System::Threading;

void main()
{
   Thread::CurrentThread->CurrentCulture = CultureInfo::CreateSpecificCulture("en-US");
   Console::WriteLine(String::Compare("A", "a", StringComparison::CurrentCulture));
   Console::WriteLine(String::Compare("A", "a", StringComparison::Ordinal));
}
// The example displays the following output: 
//       1 
//       -32
using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
      Console.WriteLine(String.Compare("A", "a", StringComparison.CurrentCulture));
      Console.WriteLine(String.Compare("A", "a", StringComparison.Ordinal));
   }
}
// The example displays the following output:
//       1
//       -32
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
      Console.WriteLine(String.Compare("A", "a", StringComparison.CurrentCulture))
      Console.WriteLine(String.Compare("A", "a", StringComparison.Ordinal))
   End Sub
End Module
' The example displays the following output:
'       1                                                                                     
'       -32

.NET 支援 word、 字串和序數排序規則:.NET supports word, string, and ordinal sort rules:

  • 文字排序執行區分文化特性比較的字串,其中某些非英數字元的 Unicode 字元可能會被獲指派特殊的權重。A word sort performs a culture-sensitive comparison of strings in which certain nonalphanumeric Unicode characters might have special weights assigned to them. 比方說,連字號 (-) 可能很小的權重,讓"coop"和"co-op"會相互並排顯示已排序的清單中,指派給它。For example, the hyphen (-) might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. 取得一份String方法來比較兩個字串使用字組排序規則,請參閱依分類的字串作業一節。For a list of the String methods that compare two strings using word sort rules, see the String operations by category section.

  • 字串排序也會執行區分文化特性的比較。A string sort also performs a culture-sensitive comparison. 就像是文字排序,只不過沒有特殊案例,而且所有的非英數符號前面所有英數字元的 Unicode 字元。It is similar to a word sort, except that there are no special cases, and all nonalphanumeric symbols come before all alphanumeric Unicode characters. 可以藉由呼叫中使用字串的排序規則比較兩個字串CompareInfo.Compare方法的多載options參數所提供的值CompareOptions.StringSortTwo strings can be compared using string sort rules by calling the CompareInfo.Compare method overloads that have an options parameter that is supplied a value of CompareOptions.StringSort. 請注意,這是.NET 提供要比較兩個字串時,使用字串的排序規則的唯一方法。Note that this is the only method that .NET provides to compare two strings using string sort rules.

  • 序數排序比較根據每個數值的字串Char字串中的物件。An ordinal sort compares strings based on the numeric value of each Char object in the string. 小寫和大寫字元的版本具有不同的字碼指標是,會自動區分大小寫的序數比較。An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. 不過,如果案例並不重要,您可以指定會忽略大小寫的序數比較。However, if case is not important, you can specify an ordinal comparison that ignores case. 這就相當於將字串轉換成大寫使用文化特性而異,然後在結果上執行序數比較。This is equivalent to converting the string to uppercase by using the invariant culture and then performing an ordinal comparison on the result. 取得一份String方法來比較兩個字串採用序數排序規則,請參閱依分類的字串作業一節。For a list of the String methods that compare two strings using ordinal sort rules, see the String operations by category section.

區分文化特性的比較是明確或隱含地使用任何比較CultureInfo物件,包括而異的文化特性由CultureInfo.InvariantCulture屬性。A culture-sensitive comparison is any comparison that explicitly or implicitly uses a CultureInfo object, including the invariant culture that is specified by the CultureInfo.InvariantCulture property. 隱含的文化特性是所指定的目前文化特性Thread.CurrentCultureCultureInfo.CurrentCulture屬性。The implicit culture is the current culture, which is specified by the Thread.CurrentCulture and CultureInfo.CurrentCulture properties. 沒有相當大的差異,在排序次序的字母字元 (亦即,字元Char.IsLetter屬性會傳回true) 跨文化特性。There is considerable variation in the sort order of alphabetic characters (that is, characters for which the Char.IsLetter property returns true) across cultures. 您可以指定使用特定文化特性的慣例,藉由提供區分文化特性比較CultureInfo這類物件的字串比較方法Compare(String, String, CultureInfo, CompareOptions)You can specify a culture-sensitive comparison that uses the conventions of a specific culture by supplying a CultureInfo object to a string comparison method such as Compare(String, String, CultureInfo, CompareOptions). 您可以指定使用目前的文化特性的慣例,藉由提供區分文化特性比較StringComparison.CurrentCultureStringComparison.CurrentCultureIgnoreCase,或任何成員CompareOptions以外的列舉型別CompareOptions.OrdinalCompareOptions.OrdinalIgnoreCase適當多載Compare方法。You can specify a culture-sensitive comparison that uses the conventions of the current culture by supplying StringComparison.CurrentCulture, StringComparison.CurrentCultureIgnoreCase, or any member of the CompareOptions enumeration other than CompareOptions.Ordinal or CompareOptions.OrdinalIgnoreCase to an appropriate overload of the Compare method. 區分文化特性的比較是通常適用於排序,而不是序數比較。A culture-sensitive comparison is generally appropriate for sorting whereas an ordinal comparison is not. 序數比較是通常適用於判斷兩個字串是否相等 (也就是判斷身分識別) 而不是區分文化特性的比較。An ordinal comparison is generally appropriate for determining whether two strings are equal (that is, for determining identity) whereas a culture-sensitive comparison is not.

下列範例說明區分文化特性和序數比較之間的差異。The following example illustrates the difference between culture-sensitive and ordinal comparison. 此範例會評估三個字串、"Apple"、"Æble,"和"AEble",使用序數比較和 DA-DK 和 EN-US 文化特性的慣例 (每個都是預設文化特性時Compare方法呼叫)。The example evaluates three strings, "Apple", "Æble", and "AEble", using ordinal comparison and the conventions of the da-DK and en-US cultures (each of which is the default culture at the time the Compare method is called). 因為丹麥文語言字元"Æ 」 視為個別的字母,而且會依字母順序的"Z"後面排序,字串"Æble 」 大於"Apple"。Because the Danish language treats the character "Æ" as an individual letter and sorts it after "Z" in the alphabet, the string "Æble" is greater than "Apple". 不過,"Æble"是不被視為相等於"AEble 」,使"Æble 」 也是大於"AEble 」。However, "Æble" is not considered equivalent to "AEble", so "Æble" is also greater than "AEble". EN-US 文化特性不包含字母"Æ",但會將其視為相當於"AE",其中說明為什麼 「 Æble"小於"Apple"但為等於"AEble 」。The en-US culture doesn't include the letter"Æ" but treats it as equivalent to "AE", which explains why "Æble" is less than "Apple" but equal to "AEble". 序數比較,相反地,會視為必須小於"Æble 」 和"Æble 「 大於 」 AEble"的"Apple"。Ordinal comparison, on the other hand, considers "Apple" to be less than "Æble", and "Æble" to be greater than "AEble".

using System;
using System.Globalization;
using System.Threading;

public class CompareStringSample
{
   public static void Main()
   {
      string str1 = "Apple";
      string str2 = "Æble"; 
      string str3 = "AEble";
      
      // Set the current culture to Danish in Denmark.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
      Console.WriteLine("Current culture: {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, String.Compare(str1, str2));
      Console.WriteLine("Comparison of {0} with {1}: {2}\n", 
                        str2, str3, String.Compare(str2, str3));
      
      // Set the current culture to English in the U.S.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      Console.WriteLine("Current culture: {0}", 
                        CultureInfo.CurrentCulture.Name);
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, String.Compare(str1, str2));
      Console.WriteLine("Comparison of {0} with {1}: {2}\n", 
                        str2, str3, String.Compare(str2, str3));
      
      // Perform an ordinal comparison.
      Console.WriteLine("Ordinal comparison");
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, 
                        String.Compare(str1, str2, StringComparison.Ordinal));
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str2, str3, 
                        String.Compare(str2, str3, StringComparison.Ordinal));
   }
}
// The example displays the following output:
//       Current culture: da-DK
//       Comparison of Apple with Æble: -1
//       Comparison of Æble with AEble: 1
//       
//       Current culture: en-US
//       Comparison of Apple with Æble: 1
//       Comparison of Æble with AEble: 0
//       
//       Ordinal comparison
//       Comparison of Apple with Æble: -133
//       Comparison of Æble with AEble: 133
Imports System.Globalization
Imports System.Threading

Public Module Example
   Public Sub Main()
      Dim str1 As String = "Apple"
      Dim str2 As String = "Æble"
      Dim str3 As String = "AEble"
      
      ' Set the current culture to Danish in Denmark.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("da-DK")
      Console.WriteLine("Current culture: {0}", 
                        CultureInfo.CurrentCulture.Name)
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, String.Compare(str1, str2))
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str2, str3, String.Compare(str2, str3))
      Console.WriteLine()
      
      ' Set the current culture to English in the U.S.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
      Console.WriteLine("Current culture: {0}", 
                        CultureInfo.CurrentCulture.Name)
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, String.Compare(str1, str2))
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str2, str3, String.Compare(str2, str3))
      Console.WriteLine()
      
      ' Perform an ordinal comparison.
      Console.WriteLine("Ordinal comparison")
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str1, str2, 
                        String.Compare(str1, str2, StringComparison.Ordinal))
      Console.WriteLine("Comparison of {0} with {1}: {2}", 
                        str2, str3, 
                        String.Compare(str2, str3, StringComparison.Ordinal))
   End Sub
End Module
' The example displays the following output:
'       Current culture: da-DK
'       Comparison of Apple with Æble: -1
'       Comparison of Æble with AEble: 1
'       
'       Current culture: en-US
'       Comparison of Apple with Æble: 1
'       Comparison of Æble with AEble: 0
'       
'       Ordinal comparison
'       Comparison of Apple with Æble: -133
'       Comparison of Æble with AEble: 133

您可以使用下列指導方針來選擇適當的排序或字串比較方法:Use the following general guidelines to choose an appropriate sorting or string comparison method:

  • 如果您想根據使用者的文化特性來排序字串,您應該將根據目前的文化特性的慣例加以排序。If you want the strings to be ordered based on the user's culture, you should order them based on the conventions of the current culture. 如果使用者的文化特性變更,排序字串的順序將也會據此變更。If the user's culture changes, the order of sorted strings will also change accordingly. 比方說,同義字應用程式應該一律會排序根據使用者的文化特性的字。For example, a thesaurus application should always sort words based on the user's culture.

  • 如果您想要排序的字串依據特定文化特性的慣例,您應該依它們提供CultureInfo物件,表示該文化特性的比較方法。If you want the strings to be ordered based on the conventions of a specific culture, you should order them by supplying a CultureInfo object that represents that culture to a comparison method. 比方說,在設計來教導學生特定語言的應用程式,您想要排序的字串根據其中一個使用該語言的文化特性的慣例。For example, in an application designed to teach students a particular language, you want strings to be ordered based on the conventions of one of the cultures that speaks that language.

  • 如果您想維持不變,跨文化特性字串順序時,您應該根據文化特性而異的慣例加以排序,或使用序數比較。If you want the order of strings to remain unchanged across cultures, you should order them based on the conventions of the invariant culture or use an ordinal comparison. 例如,您會使用序數排序來組織檔案、 處理程序、 mutex 的名稱或具名管道。For example, you would use an ordinal sort to organize the names of files, processes, mutexes, or named pipes.

  • 如需牽涉到安全性決策 (例如使用者名稱是否有效) 的比較,您應該一律執行序數測試是否相等藉由呼叫的多載Equals方法。For a comparison that involves a security decision (such as whether a username is valid), you should always perform an ordinal test for equality by calling an overload of the Equals method.

注意

區分文化特性的排序和大小寫字串比較中使用的規則視.NET 版本而定。The culture-sensitive sorting and casing rules used in string comparison depend on the version of the .NET. 在.NET Framework 4.5 和更新版本上執行Windows 8Windows 8操作系統、 排序、 大小寫、 正規化和 Unicode 字元資訊符合 Unicode 6.0 標準。In the .NET Framework 4.5 and later versions running on the Windows 8Windows 8 operating system, sorting, casing, normalization, and Unicode character information conforms to the Unicode 6.0 standard. 其他 Windows 作業系統在系統上,其符合標準的 Unicode 5.0。On other Windows operating systems, it conforms to the Unicode 5.0 standard. 在.NET Core,這取決於基礎作業系統所支援的 Unicode 標準版本。On .NET Core, it depends on the version of the Unicode Standard supported by the underlying operating system.

如需 word、 字串和序數排序規則的詳細資訊,請參閱System.Globalization.CompareOptions主題。For more information about word, string, and ordinal sort rules, see the System.Globalization.CompareOptions topic. 如需何時使用每個規則,其他建議,請參閱使用字串的最佳做法For additional recommendations on when to use each rule, see Best Practices for Using Strings.

一般情況下,您不呼叫字串比較方法,例如Compare直接以判斷字串的排序次序。Ordinarily, you don't call string comparison methods such as Compare directly to determine the sort order of strings. 相反地,例如排序方法會呼叫比較方法Array.SortList<T>.SortInstead, comparison methods are called by sorting methods such as Array.Sort or List<T>.Sort. 下列範例執行四個不同排序作業 (使用目前文化特性、 使用區分文化特性的字組排序、 序數排序,以及使用文化特性而異的字串排序字組排序),而不需要明確呼叫字串比較方法,雖然它們指定要使用的比較類型。The following example performs four different sorting operations (word sort using the current culture, word sort using the invariant culture, ordinal sort, and string sort using the invariant culture) without explicitly calling a string comparison method, although they do specify the type of comparison to use. 請注意,每一種排序會產生唯一的字串,其陣列中所用的順序。Note that each type of sort produces a unique ordering of strings in its array.

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Globalization;

// IComparer<String> implementation to perform string sort. 
ref class SCompare : System::Collections::Generic::IComparer<String^>
{
public:
   SCompare() {};

   virtual int Compare(String^ x, String^ y)
   {
      return CultureInfo::CurrentCulture->CompareInfo->Compare(x, y, CompareOptions::StringSort);
   }
};

void main()
{
   array<String^>^ strings = gcnew array<String^> { "coop", "co-op", "cooperative", 
                                                    L"co\x00ADoperative", L"c�ur", "coeur" };

   // Perform a word sort using the current (en-US) culture. 
   array<String^>^ current = gcnew array<String^>(strings->Length); 
   strings->CopyTo(current, 0); 
   Array::Sort(current, StringComparer::CurrentCulture);

   // Perform a word sort using the invariant culture. 
   array<String^>^ invariant = gcnew array<String^>(strings->Length);
   strings->CopyTo(invariant, 0); 
   Array::Sort(invariant, StringComparer::InvariantCulture);

   // Perform an ordinal sort. 
   array<String^>^ ordinal = gcnew array<String^>(strings->Length);
   strings->CopyTo(ordinal, 0); 
   Array::Sort(ordinal, StringComparer::Ordinal);

   // Perform a string sort using the current culture. 
   array<String^>^ stringSort = gcnew array<String^>(strings->Length);
   strings->CopyTo(stringSort, 0); 
   Array::Sort(stringSort, gcnew SCompare());

   // Display array values
   Console::WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}\n", 
                     "Original", "Word Sort", "Invariant Word", 
                     "Ordinal Sort", "String Sort");
   for (int ctr = 0; ctr < strings->Length; ctr++)
      Console::WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}", 
                         strings[ctr], current[ctr], invariant[ctr], 
                         ordinal[ctr], stringSort[ctr] );          
}
// The example displays the following output: 
//         Original     Word Sort  Invariant Word  Ordinal Sort   String Sort 
//     
//             coop          c�ur            c�ur         co-op         co-op 
//            co-op         coeur           coeur         coeur          c�ur 
//      cooperative          coop            coop          coop         coeur 
//      co�operative         co-op           co-op   cooperative          coop 
//             c�ur   cooperative     cooperative   co�operative   cooperative 
//            coeur   co�operative     co�operative          c�ur   co�operative
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
 
public class Example
{
   public static void Main()
   {
      string[] strings = { "coop", "co-op", "cooperative", 
                           "co\u00ADoperative", "cœur", "coeur" };

      // Perform a word sort using the current (en-US) culture.
      string[] current = new string[strings.Length]; 
      strings.CopyTo(current, 0); 
      Array.Sort(current, StringComparer.CurrentCulture);

      // Perform a word sort using the invariant culture.
      string[] invariant = new string[strings.Length];
      strings.CopyTo(invariant, 0); 
      Array.Sort(invariant, StringComparer.InvariantCulture);

      // Perform an ordinal sort.
      string[] ordinal = new string[strings.Length];
      strings.CopyTo(ordinal, 0); 
      Array.Sort(ordinal, StringComparer.Ordinal);

      // Perform a string sort using the current culture.
      string[] stringSort = new string[strings.Length];
      strings.CopyTo(stringSort, 0); 
      Array.Sort(stringSort, new SCompare());

      // Display array values
      Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}\n", 
                        "Original", "Word Sort", "Invariant Word", 
                        "Ordinal Sort", "String Sort");
      for (int ctr = 0; ctr < strings.Length; ctr++)
         Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}", 
                           strings[ctr], current[ctr], invariant[ctr], 
                           ordinal[ctr], stringSort[ctr] );          
   }
}

// IComparer<String> implementation to perform string sort.
internal class SCompare : IComparer<String>
{
   public int Compare(string x, string y)
   {
      return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort);
   }
}
// The example displays the following output:
//         Original     Word Sort  Invariant Word  Ordinal Sort   String Sort
//    
//             coop          cœur            cœur         co-op         co-op
//            co-op         coeur           coeur         coeur          cœur
//      cooperative          coop            coop          coop         coeur
//     co­operative         co-op           co-op   cooperative          coop
//             cœur   cooperative     cooperative  co­operative   cooperative
//            coeur  co­operative    co­operative          cœur  co­operative
Imports System.Collections
Imports System.Collections.Generic
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim strings() As String = { "coop", "co-op", "cooperative", 
                                  "co" + ChrW(&h00AD) + "operative", 
                                  "cœur", "coeur" }

      ' Perform a word sort using the current (en-US) culture.
      Dim current(strings.Length - 1) As String  
      strings.CopyTo(current, 0) 
      Array.Sort(current, StringComparer.CurrentCulture)

      ' Perform a word sort using the invariant culture.
      Dim invariant(strings.Length - 1) As String
      strings.CopyTo(invariant, 0) 
      Array.Sort(invariant, StringComparer.InvariantCulture)

      ' Perform an ordinal sort.
      Dim ordinal(strings.Length - 1) As String
      strings.CopyTo(ordinal, 0) 
      Array.Sort(ordinal, StringComparer.Ordinal)

      ' Perform a string sort using the current culture.
      Dim stringSort(strings.Length - 1) As String
      strings.CopyTo(stringSort, 0) 
      Array.Sort(stringSort, new SCompare())

      ' Display array values
      Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}", 
                        "Original", "Word Sort", "Invariant Word", 
                        "Ordinal Sort", "String Sort")
      Console.WriteLine()
                                                      
      For ctr As Integer = 0 To strings.Length - 1
         Console.WriteLine("{0,13} {1,13} {2,15} {3,13} {4,13}", 
                           strings(ctr), current(ctr), invariant(ctr), 
                           ordinal(ctr), stringSort(ctr))   
      Next                                  
   End Sub
End Module

' IComparer<String> implementation to perform string sort.
Friend Class SCompare : Implements IComparer(Of String)
   Public Function Compare(x As String, y As String) As Integer _
                   Implements IComparer(Of String).Compare
      Return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort)
   End Function
End Class
' The example displays the following output:
'         Original     Word Sort  Invariant Word  Ordinal Sort   String Sort
'    
'             coop          cœur            cœur         co-op         co-op
'            co-op         coeur           coeur         coeur          cœur
'      cooperative          coop            coop          coop         coeur
'     co­operative         co-op           co-op   cooperative          coop
'             cœur   cooperative     cooperative  co­operative   cooperative
'            coeur  co­operative    co­operative          cœur  co­operative

提示

就內部而言,.NET 會使用排序索引鍵,以支援區分文化特性的字串比較。Internally, .NET uses sort keys to support culturally sensitive string comparison. 每一個字元在字串中的提供排序權數,包括字母、 大小寫和變音符號的數個的類別。Each character in a string is given several categories of sort weights, including alphabetic, case, and diacritic. 排序索引鍵,由SortKey類別中,提供這些加權的存放庫特定的字串。A sort key, represented by the SortKey class, provides a repository of these weights for a particular string. 如果您的應用程式會執行大量搜尋或排序在相同的字串集合上的作業,您可以藉由產生並儲存它所使用的所有字串的排序鍵來改善其效能。If your app performs a large number of searching or sorting operations on the same set of strings, you can improve its performance by generating and storing sort keys for all the strings that it uses. 需要排序或比較運算時,您會使用的排序索引鍵,而不是字串。When a sort or comparison operation is required, you use the sort keys instead of the strings. 如需詳細資訊,請參閱 SortKey 類別。For more information, see the SortKey class.

如果您未指定的字串比較的慣例,排序方法這類Array.Sort(Array)對字串執行區分文化特性,區分大小寫排序。If you don't specify a string comparison convention, sorting methods such as Array.Sort(Array) perform a culture-sensitive, case-sensitive sort on strings. 下列範例說明如何變更目前的文化特性會影響已排序字串陣列中的順序。The following example illustrates how changing the current culture affects the order of sorted strings in an array. 它會建立三個字串的陣列。It creates an array of three strings. 首先,它會設定System.Threading.Thread.CurrentThread.CurrentCulture屬性設為 EN-US 並呼叫Array.Sort(Array)方法。First, it sets the System.Threading.Thread.CurrentThread.CurrentCulture property to en-US and calls the Array.Sort(Array) method. 產生的排序次序會根據排序的英文 (美國) 文化特性的慣例。The resulting sort order is based on sorting conventions for the English (United States) culture. 接下來,範例會設定System.Threading.Thread.CurrentThread.CurrentCulture屬性設為 DA-DK 並呼叫Array.Sort方法一次。Next, the example sets the System.Threading.Thread.CurrentThread.CurrentCulture property to da-DK and calls the Array.Sort method again. 請注意如何產生的排序次序不同於 EN-US 結果因為它會使用丹麥文 (丹麥) 排序慣例。Notice how the resulting sort order differs from the en-US results because it uses the sorting conventions for Danish (Denmark).

using System;
using System.Globalization;
using System.Threading;

public class ArraySort 
{
   public static void Main(String[] args) 
   {
      // Create and initialize a new array to store the strings.
      string[] stringArray = { "Apple", "Æble", "Zebra"};

      // Display the values of the array.
      Console.WriteLine( "The original string array:");
      PrintIndexAndValues(stringArray);

      // Set the CurrentCulture to "en-US".
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      // Sort the values of the array.
      Array.Sort(stringArray);

      // Display the values of the array.
      Console.WriteLine("After sorting for the culture \"en-US\":");
      PrintIndexAndValues(stringArray); 

      // Set the CurrentCulture to "da-DK".
      Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
      // Sort the values of the Array.
      Array.Sort(stringArray);

      // Display the values of the array.
      Console.WriteLine("After sorting for the culture \"da-DK\":");
      PrintIndexAndValues(stringArray); 
   }
   public static void PrintIndexAndValues(string[] myArray)  
   {
      for (int i = myArray.GetLowerBound(0); i <= 
            myArray.GetUpperBound(0); i++ )
         Console.WriteLine("[{0}]: {1}", i, myArray[i]);
      Console.WriteLine();      
   }
}
// The example displays the following output:
//       The original string array:
//       [0]: Apple
//       [1]: Æble
//       [2]: Zebra
//       
//       After sorting for the "en-US" culture:
//       [0]: Æble
//       [1]: Apple
//       [2]: Zebra
//       
//       After sorting for the culture "da-DK":
//       [0]: Apple
//       [1]: Zebra
//       [2]: Æble
Imports System.Globalization
Imports System.IO
Imports System.Threading

Public Class TextToFile   
   Public Shared Sub Main()
      ' Creates and initializes a new array to store 
      ' these date/time objects.
      Dim stringArray() As String = { "Apple", "Æble", "Zebra"}
      
      ' Displays the values of the array.
      Console.WriteLine("The original string array:")
      PrintIndexAndValues(stringArray)
      
      ' Set the CurrentCulture to "en-US".
      Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
      ' Sort the values of the Array.
      Array.Sort(stringArray)
      
      ' Display the values of the array.
      Console.WriteLine("After sorting for the ""en-US"" culture:")
      PrintIndexAndValues(stringArray)
      
      ' Set the CurrentCulture to "da-DK".
      Thread.CurrentThread.CurrentCulture = New CultureInfo("da-DK")
      ' Sort the values of the Array.
      Array.Sort(stringArray)
      
      ' Displays the values of the Array.
      Console.WriteLine("After sorting for the culture ""da-DK"":")
      PrintIndexAndValues(stringArray)
   End Sub

   Public Shared Sub PrintIndexAndValues(myArray() As String)
      For i As Integer = myArray.GetLowerBound(0) To myArray.GetUpperBound(0)
         Console.WriteLine("[{0}]: {1}", i, myArray(i))
      Next
      Console.WriteLine()
   End Sub 
End Class
' The example displays the following output:
'       The original string array:
'       [0]: Apple
'       [1]: Æble
'       [2]: Zebra
'       
'       After sorting for the "en-US" culture:
'       [0]: Æble
'       [1]: Apple
'       [2]: Zebra
'       
'       After sorting for the culture "da-DK":
'       [0]: Apple
'       [1]: Zebra
'       [2]: Æble

警告

如果您在比較字串的主要目的是要判斷是否相等,您應該呼叫String.Equals方法。If your primary purpose in comparing strings is to determine whether they are equal, you should call the String.Equals method. 一般而言,您應該使用Equals来執行序數比較。Typically, you should use Equals to perform an ordinal comparison. String.Compare方法主要為了排序字串。The String.Compare method is intended primarily to sort strings.

字串搜尋方法,例如String.StartsWithString.IndexOf,也可以執行區分文化特性或序數字串比較。String search methods, such as String.StartsWith and String.IndexOf, also can perform culture-sensitive or ordinal string comparisons. 下列範例說明使用序數和區分文化特性的比較差異IndexOf方法。The following example illustrates the differences between ordinal and culture-sensitive comparisons using the IndexOf method. 中目前的文化特性是英文 (美國) 文化特性搜尋會視為 「 oe 」,以符合連音符號"œ"的子字串。A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". 因為選擇性連字號 (U + 00AD) 是零寬度的字元,則搜尋會將選擇性連字號視為相當於Empty和字串的開頭在找到相符項目。Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to Empty and finds a match at the beginning of the string. 序數搜尋,相反地,找不到相符項目在任一情況下。An ordinal search, on the other hand, does not find a match in either case.

using namespace System;

void FindInString(String^ s, String^ substring, StringComparison options);

void main()
{
   // Search for "oe" and "�u" in "�ufs" and "oeufs".
   String^ s1 = L"�ufs";
   String^ s2 = L"oeufs";
   FindInString(s1, "oe", StringComparison::CurrentCulture);
   FindInString(s1, "oe", StringComparison::Ordinal);
   FindInString(s2, "�u", StringComparison::CurrentCulture);
   FindInString(s2, "�u", StringComparison::Ordinal);
   Console::WriteLine();

   String^ s3 = L"co\x00ADoperative";
   FindInString(s3, L"\x00AD", StringComparison::CurrentCulture);
   FindInString(s3, L"\x00AD", StringComparison::Ordinal);
}

void FindInString(String^ s, String^ substring, StringComparison options)
{
   int result = s->IndexOf(substring, options);
   if (result != -1)
      Console::WriteLine("'{0}' found in {1} at position {2}", 
                        substring, s, result);
   else
      Console::WriteLine("'{0}' not found in {1}", 
                        substring, s);                                                  
}
// The example displays the following output:
//      'oe' found in oufs at position 0
//      'oe' not found in oufs
//      'ou' found in oeufs at position 0
//      'ou' not found in oeufs
//
//      '-' found in co-operative at position 0
//      '-' found in co-operative at position 2
using System;

public class Example
{
   public static void Main()
   {
      // Search for "oe" and "œu" in "œufs" and "oeufs".
      string s1 = "œufs";
      string s2 = "oeufs";
      FindInString(s1, "oe", StringComparison.CurrentCulture);
      FindInString(s1, "oe", StringComparison.Ordinal);
      FindInString(s2, "œu", StringComparison.CurrentCulture);
      FindInString(s2, "œu", StringComparison.Ordinal);
      Console.WriteLine();
      
      string s3 = "co\u00ADoperative";
      FindInString(s3, "\u00AD", StringComparison.CurrentCulture);
      FindInString(s3, "\u00AD", StringComparison.Ordinal);
   }

   private static void FindInString(string s, string substring, StringComparison options)
   {
      int result = s.IndexOf(substring, options);
      if (result != -1)
         Console.WriteLine("'{0}' found in {1} at position {2}", 
                           substring, s, result);
      else
         Console.WriteLine("'{0}' not found in {1}", 
                           substring, s);                                                  
   }
}
// The example displays the following output:
//       'oe' found in œufs at position 0
//       'oe' not found in œufs
//       'œu' found in oeufs at position 0
//       'œu' not found in oeufs
//       
//       '­' found in co­operative at position 0
//       '­' found in co­operative at position 2
Module Example
   Public Sub Main()
      ' Search for "oe" and "œu" in "œufs" and "oeufs".
      Dim s1 As String = "œufs"
      Dim s2 As String = "oeufs"
      FindInString(s1, "oe", StringComparison.CurrentCulture)
      FindInString(s1, "oe", StringComparison.Ordinal)
      FindInString(s2, "œu", StringComparison.CurrentCulture)
      FindInString(s2, "œu", StringComparison.Ordinal)
      Console.WriteLine()
      
      Dim softHyphen As String = ChrW(&h00AD)
      Dim s3 As String = "co" + softHyphen + "operative"
      FindInString(s3, softHyphen, StringComparison.CurrentCulture)
      FindInString(s3, softHyphen, StringComparison.Ordinal)
   End Sub

   Private Sub FindInString(s As String, substring As String, 
                            options As StringComparison)
      Dim result As Integer = s.IndexOf(substring, options)
      If result <> -1
         Console.WriteLine("'{0}' found in {1} at position {2}", 
                           substring, s, result)
      Else
         Console.WriteLine("'{0}' not found in {1}", 
                           substring, s)
      End If                                                                          
   End Sub
End Module
' The example displays the following output:
'       'oe' found in œufs at position 0
'       'oe' not found in œufs
'       'œu' found in oeufs at position 0
'       'œu' not found in oeufs
'       
'       '­' found in co­operative at position 0
'       '­' found in co­operative at position 2

搜尋字串Searching Strings

字串搜尋方法,例如String.StartsWithString.IndexOf,也可以執行區分文化特性或指定的字串中找到的序數字串比較,以判斷是否在字元或子字串。String search methods, such as String.StartsWith and String.IndexOf, also can perform culture-sensitive or ordinal string comparisons to determine whether a character or substring is found in a specified string.

中的搜尋方法String類別的搜尋的個別字元,例如IndexOf方法,或其中一個的一組字元,例如IndexOfAny方法中,所有執行的序數搜尋。The search methods in the String class that search for an individual character, such as the IndexOf method, or one of a set of characters, such as the IndexOfAny method, all perform an ordinal search. 若要執行區分文化特性的搜尋的字元,您必須呼叫CompareInfo方法,例如CompareInfo.IndexOf(String, Char)CompareInfo.LastIndexOf(String, Char)To perform a culture-sensitive search for a character, you must call a CompareInfo method such as CompareInfo.IndexOf(String, Char) or CompareInfo.LastIndexOf(String, Char). 請注意,搜尋字元,使用序數和區分文化特性比較的結果可能大不相同。Note that the results of searching for a character using ordinal and culture-sensitive comparison can be very different. 比方說,搜尋預先組成的 Unicode 字元,例如連音符號"Æ 」 (U + 00 C 6) 可能會比對出現在正確的順序,例如"AE"及其元件的任何 (U + 041U + 0045),根據文化特性。For example, a search for a precomposed Unicode character such as the ligature "Æ" (U+00C6) might match any occurrence of its components in the correct sequence, such as "AE" (U+041U+0045), depending on the culture. 下列範例說明之間的差異String.IndexOf(Char)CompareInfo.IndexOf(String, Char)方法搜尋的個別字元時。The following example illustrates the difference between the String.IndexOf(Char) and CompareInfo.IndexOf(String, Char) methods when searching for an individual character. 連音符號"æ 」 (U + 00E6) 中找到字串"空照圖 」 時使用 EN-US 文化特性的慣例,但不是使用時 DA-DK 文化特性的慣例或執行序數比較時。The ligature "æ" (U+00E6) is found in the string "aerial" when using the conventions of the en-US culture, but not when using the conventions of the da-DK culture or when performing an ordinal comparison.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      String[] cultureNames = { "da-DK", "en-US" };
      CompareInfo ci;
      String str = "aerial";
      Char ch = 'æ';  // U+00E6
      
      Console.Write("Ordinal comparison -- ");
      Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
                        str.IndexOf(ch));
      
      foreach (var cultureName in cultureNames) {
         ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo;
         Console.Write("{0} cultural comparison -- ", cultureName);
         Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
                           ci.IndexOf(str, ch));
      }
   }
}
// The example displays the following output:
//       Ordinal comparison -- Position of 'æ' in aerial: -1
//       da-DK cultural comparison -- Position of 'æ' in aerial: -1
//       en-US cultural comparison -- Position of 'æ' in aerial: 0
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "da-DK", "en-US" }
      Dim ci As CompareInfo
      Dim str As String = "aerial"
      Dim ch As Char = "æ"c  ' U+00E6
      
      Console.Write("Ordinal comparison -- ")
      Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
                        str.IndexOf(ch))
      
      For Each cultureName In cultureNames
         ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo
         Console.Write("{0} cultural comparison -- ", cultureName)
         Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str,
                           ci.IndexOf(str, ch))
      Next
   End Sub
End Module
' The example displays the following output:
'       Ordinal comparison -- Position of 'æ' in aerial: -1
'       da-DK cultural comparison -- Position of 'æ' in aerial: -1
'       en-US cultural comparison -- Position of 'æ' in aerial: 0

相反地,String類別搜尋字串,而不是字元執行區分文化特性的搜尋,如果搜尋選項未明確指定類型的參數的方法StringComparisonOn the other hand, String class methods that search for a string rather than a character perform a culture-sensitive search if search options are not explicitly specified by a parameter of type StringComparison. 唯一的例外狀況是Contains,會執行序數的搜尋。The sole exception is Contains, which performs an ordinal search.

測試相等Testing for equality

使用String.Compare方法,以判斷兩個字串在排序次序中的關聯性。Use the String.Compare method to determine the relationship of two strings in the sort order. 一般而言,這是區分文化特性的作業。Typically, this is a culture-sensitive operation. 相反地,呼叫String.Equals方法來測試是否相等。In contrast, call the String.Equals method to test for equality. 因為相等測試通常會比對使用者輸入一些已知的字串,例如有效的使用者名稱、 密碼或檔案系統路徑,但它通常是序數的作業。Because the test for equality usually compares user input with some known string, such as a valid user name, a password, or a file system path, it is typically an ordinal operation.

警告

可以藉由呼叫測試是否相等String.Compare方法,並判斷傳回的值是否為零。It is possible to test for equality by calling the String.Compare method and determining whether the return value is zero. 不過,不建議這種做法。However, this practice is not recommended. 若要判斷兩個字串是否相等,您應該呼叫其中一個多載String.Equals方法。To determine whether two strings are equal, you should call one of the overloads of the String.Equals method. 慣用的多載,以呼叫為任一個執行個體Equals(String, StringComparison)方法或靜態Equals(String, String, StringComparison)方法,因為這兩種方法都包含System.StringComparison明確指定的比較類型的參數。The preferred overload to call is either the instance Equals(String, StringComparison) method or the static Equals(String, String, StringComparison) method, because both methods include a System.StringComparison parameter that explicitly specifies the type of comparison.

下列範例說明執行區分文化特性比較相等時應該改為使用其中一個為序數的危險。The following example illustrates the danger of performing a culture-sensitive comparison for equality when an ordinal one should be used instead. 在此情況下,程式碼的意圖是禁止執行不區分大小寫的 URL,以使用字串"FILE:// 開頭比較的方式以"FILE:// 或"file:// 開頭的 Url 中的檔案系統存取權。In this case, the intent of the code is to prohibit file system access from URLs that begin with "FILE://" or "file://" by performing a case-insensitive comparison of the beginning of a URL with the string "FILE://". 不過,如果以"file:// 開頭的 URL 上使用土耳其文 (土耳其) 文化特性執行區分文化特性的比較,相等的比較會失敗,因為土耳其文的大寫對等的小寫字母"i"為"i"而不是"I"。However, if a culture-sensitive comparison is performed using the Turkish (Turkey) culture on a URL that begins with "file://", the comparison for equality fails, because the Turkish uppercase equivalent of the lowercase "i" is "İ" instead of "I". 如此一來,不小心允許檔案系統存取權。As a result, file system access is inadvertently permitted. 相反地,如果執行序數比較,則成功的相等比較,和檔案系統存取遭到拒絕。On the other hand, if an ordinal comparison is performed, the comparison for equality succeeds, and file system access is denied.

using namespace System;
using namespace System::Globalization;
using namespace System::Threading;

bool TestForEquality(String^ str, StringComparison cmp);

void main()
{
   Thread::CurrentThread->CurrentCulture = CultureInfo::CreateSpecificCulture("tr-TR");      

   String^ filePath = "file://c:/notes.txt";

   Console::WriteLine("Culture-sensitive test for equality:");
   if (! TestForEquality(filePath, StringComparison::CurrentCultureIgnoreCase))
      Console::WriteLine("Access to {0} is allowed.", filePath);
   else
      Console::WriteLine("Access to {0} is not allowed.", filePath);

   Console::WriteLine("\nOrdinal test for equality:");
   if (! TestForEquality(filePath, StringComparison::OrdinalIgnoreCase))
      Console::WriteLine("Access to {0} is allowed.", filePath);
   else
      Console::WriteLine("Access to {0} is not allowed.", filePath);
}

bool TestForEquality(String^ str, StringComparison cmp)
{
      int position = str->IndexOf("://");
      if (position < 0) return false;

      String^ substring = str->Substring(0, position);  
      return substring->Equals("FILE", cmp);
}
// The example displays the following output: 
//       Culture-sensitive test for equality: 
//       Access to file://c:/notes.txt is allowed. 
//        
//       Ordinal test for equality: 
//       Access to file://c:/notes.txt is not allowed.
using System;
using System.Globalization;
using System.Threading;

public class Example
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR");      

      string filePath = "file://c:/notes.txt";
      
      Console.WriteLine("Culture-sensitive test for equality:");
      if (! TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase))
         Console.WriteLine("Access to {0} is allowed.", filePath);
      else
         Console.WriteLine("Access to {0} is not allowed.", filePath);
      
      Console.WriteLine("\nOrdinal test for equality:");
      if (! TestForEquality(filePath, StringComparison.OrdinalIgnoreCase))
         Console.WriteLine("Access to {0} is allowed.", filePath);
      else
         Console.WriteLine("Access to {0} is not allowed.", filePath);
   }

   private static bool TestForEquality(string str, StringComparison cmp)
   {
      int position = str.IndexOf("://");
      if (position < 0) return false;

      string substring = str.Substring(0, position);  
      return substring.Equals("FILE", cmp);
   }
}
// The example displays the following output:
//       Culture-sensitive test for equality:
//       Access to file://c:/notes.txt is allowed.
//       
//       Ordinal test for equality:
//       Access to file://c:/notes.txt is not allowed.
Imports System.Globalization
Imports System.Threading

Module Example
   Public Sub Main()
      Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR")      

      Dim filePath As String = "file://c:/notes.txt"
      
      Console.WriteLine("Culture-sensitive test for equality:")
      If Not TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase) Then
         Console.WriteLine("Access to {0} is allowed.", filePath)
      Else
         Console.WriteLine("Access to {0} is not allowed.", filePath)
      End If       
      Console.WriteLine()
      
      Console.WriteLine("Ordinal test for equality:")
      If Not TestForEquality(filePath, StringComparison.OrdinalIgnoreCase) Then
         Console.WriteLine("Access to {0} is allowed.", filePath)
      Else
         Console.WriteLine("Access to {0} is not allowed.", filePath)
      End If       
   End Sub
   
   Private Function TestForEquality(str As String, cmp As StringComparison) As Boolean
      Dim position As Integer = str.IndexOf("://")
      If position < 0 Then Return False

      Dim substring As String = str.Substring(0, position)  
      Return substring.Equals("FILE", cmp)
   End Function
End Module
' The example displays the following output:
'       Culture-sensitive test for equality:
'       Access to file://c:/notes.txt is allowed.
'       
'       Ordinal test for equality:
'       Access to file://c:/notes.txt is not allowed.

正規化Normalization

某些 Unicode 字元有多種表示。Some Unicode characters have multiple representations. 例如,任何下列的字碼指標可以代表字母"ắ 」:For example, any of the following code points can represent the letter "ắ":

  • U+1EAFU+1EAF

  • U+0103 U+0301U+0103 U+0301

  • U+0061 U+0306 U+0301U+0061 U+0306 U+0301

搜尋、 排序、 比對,和其他字串作業,會讓複雜的單一字元的多種表示。Multiple representations for a single character complicate searching, sorting, matching, and other string operations.

Unicode 標準會定義稱為傳回一個的二進位表示法的 Unicode 字元的任何其對等的二進位表示法的正規化程序。The Unicode standard defines a process called normalization that returns one binary representation of a Unicode character for any of its equivalent binary representations. 正規化可以使用數種演算法,稱為正規化表單,可遵循不同的規則。Normalization can use several algorithms, called normalization forms, that follow different rules. .NET 支援的 Unicode 正規化表單 C、 D、 KC 和 KD。.NET supports Unicode normalization forms C, D, KC, and KD. 當字串已經正規化成相同的正規化格式時,他們可以使用序數比較來比較。When strings have been normalized to the same normalization form, they can be compared by using ordinal comparison.

序數比較是對應的 Unicode 純量值的二進位比較Char每個字串中的物件。An ordinal comparison is a binary comparison of the Unicode scalar value of corresponding Char objects in each string. String類別包含數種方法,可以執行序數比較,包括下列:The String class includes a number of methods that can perform an ordinal comparison, including the following:

您可以判斷字串是否會正規化為正規化格式 C 藉由呼叫String.IsNormalized()方法,或者您可以呼叫String.IsNormalized(NormalizationForm)方法,以判斷是否要將字串標準化為指定的正規化格式。You can determine whether a string is normalized to normalization form C by calling the String.IsNormalized() method, or you can call the String.IsNormalized(NormalizationForm) method to determine whether a string is normalized to a specified normalization form. 您也可以呼叫String.Normalize()方法,以將字串轉換為正規化格式 C,或您可以呼叫String.Normalize(NormalizationForm)方法,以將字串轉換為指定的正規化格式。You can also call the String.Normalize() method to convert a string to normalization form C, or you can call the String.Normalize(NormalizationForm) method to convert a string to a specified normalization form. 逐步將正規化和比較字串的詳細資訊,請參閱Normalize()Normalize(NormalizationForm)方法。For step-by-step information about normalizing and comparing strings, see the Normalize() and Normalize(NormalizationForm) methods.

下列的簡單範例說明字串正規化。The following simple example illustrates string normalization. 它會以三個不同的方式,在三個不同的字串,定義字母"ố 」,並使用以判斷每個字串,不同於其他兩個字串的序數比較相等。It defines the letter "ố" in three different ways in three different strings, and uses an ordinal comparison for equality to determine that each string differs from the other two strings. 它接著將每個字串轉換成支援的正規化格式,並再次執行每個字串的序數比較,為指定的正規化格式。It then converts each string to the supported normalization forms, and again performs an ordinal comparison of each string in a specified normalization form. 在每個案例中,第二項測試相等; 會顯示字串相等。In each case, the second test for equality shows that the strings are equal.

using namespace System;
using namespace System::Globalization;
using namespace System::IO;
using namespace System::Text;

public ref class Example
{
private:
   StreamWriter^ sw;

   void TestForEquality(... array<String^>^  words)
   {
      for (int ctr = 0; ctr <= words->Length - 2; ctr++)
         for (int ctr2 = ctr + 1; ctr2 <= words->Length - 1; ctr2++) 
            sw->WriteLine("{0} ({1}) = {2} ({3}): {4}", 
                         words[ctr], ShowBytes(words[ctr]),
                         words[ctr2], ShowBytes(words[ctr2]),
                         words[ctr]->Equals(words[ctr2], StringComparison::Ordinal));
   }

   String^ ShowBytes(String^ str)
   {
      String^ result = nullptr;
      for each (Char ch in str)
         result += String::Format("{0} ", Convert::ToUInt16(ch).ToString("X4")); 
      return result->Trim();            
   } 

   array<String^>^ NormalizeStrings(NormalizationForm nf, ... array<String^>^ words)
   {
      for (int ctr = 0; ctr < words->Length; ctr++)
         if (! words[ctr]->IsNormalized(nf))
            words[ctr] = words[ctr]->Normalize(nf); 
      return words;   
   }

public: 
   void Execute()
   {
      sw = gcnew StreamWriter(".\\TestNorm1.txt");

      // Define three versions of the same word.  
      String^ s1 = L"sống";        // create word with U+1ED1 
      String^ s2 = L"s\x00F4\x0301ng";
      String^ s3 = L"so\x0302\x0301ng";

      TestForEquality(s1, s2, s3);      
      sw->WriteLine();

      // Normalize and compare strings using each normalization form. 
      for each (String^ formName in Enum::GetNames(NormalizationForm::typeid))
      {
         sw->WriteLine("Normalization {0}:\n", formName); 
         NormalizationForm nf = (NormalizationForm) Enum::Parse(NormalizationForm::typeid, formName);
         array<String^>^ sn = NormalizeStrings(nf, s1, s2, s3 );
         TestForEquality(sn);           
         sw->WriteLine("\n");                                        
      }

      sw->Close(); 
   }
};

void main()
{
   Example^ ex = gcnew Example();
   ex->Execute();
}
// The example produces the following output:
// The example displays the following output: 
//       sống (0073 1ED1 006E 0067) = sống (0073 00F4 0301 006E 0067): False 
//       sống (0073 1ED1 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False 
//       sống (0073 00F4 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False 
//        
//       Normalization FormC: 
//        
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True 
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True 
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True 
//        
//        
//       Normalization FormD: 
//        
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True 
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True 
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True 
//        
//        
//       Normalization FormKC: 
//        
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True 
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True 
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True 
//        
//        
//       Normalization FormKD: 
//        
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True 
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True 
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
using System;
using System.Globalization;
using System.IO;
using System.Text;

public class Example
{
   private static StreamWriter sw;
   
   public static void Main()
   {
      sw = new StreamWriter(@".\TestNorm1.txt");

      // Define three versions of the same word. 
      string s1 = "sống";        // create word with U+1ED1
      string s2 = "s\u00F4\u0301ng";
      string s3 = "so\u0302\u0301ng";

      TestForEquality(s1, s2, s3);      
      sw.WriteLine();

      // Normalize and compare strings using each normalization form.
      foreach (string formName in Enum.GetNames(typeof(NormalizationForm)))
      {
         sw.WriteLine("Normalization {0}:\n", formName); 
         NormalizationForm nf = (NormalizationForm) Enum.Parse(typeof(NormalizationForm), formName);
         string[] sn = NormalizeStrings(nf, s1, s2, s3);
         TestForEquality(sn);           
         sw.WriteLine("\n");                                        
      }
      
      sw.Close();   
   }

   private static void TestForEquality(params string[] words)
   {
      for (int ctr = 0; ctr <= words.Length - 2; ctr++)
         for (int ctr2 = ctr + 1; ctr2 <= words.Length - 1; ctr2++) 
            sw.WriteLine("{0} ({1}) = {2} ({3}): {4}", 
                         words[ctr], ShowBytes(words[ctr]),
                         words[ctr2], ShowBytes(words[ctr2]),
                         words[ctr].Equals(words[ctr2], StringComparison.Ordinal));
   }

   private static string ShowBytes(string str)
   {
      string result = null;
      foreach (var ch in str)
         result += String.Format("{0} ", Convert.ToUInt16(ch).ToString("X4")); 
      return result.Trim();            
   } 
   
   private static string[] NormalizeStrings(NormalizationForm nf, params string[] words)
   {
      for (int ctr = 0; ctr < words.Length; ctr++)
         if (! words[ctr].IsNormalized(nf))
            words[ctr] = words[ctr].Normalize(nf); 
      return words;   
   }
}
// The example displays the following output:
//       sống (0073 1ED1 006E 0067) = sống (0073 00F4 0301 006E 0067): False
//       sống (0073 1ED1 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
//       sống (0073 00F4 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
//       
//       Normalization FormC:
//       
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       
//       
//       Normalization FormD:
//       
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       
//       
//       Normalization FormKC:
//       
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
//       
//       
//       Normalization FormKD:
//       
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
//       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
Imports System.Globalization
Imports System.IO
Imports System.Text

Module Example
   Private sw As StreamWriter
       
   Public Sub Main()
      sw = New StreamWriter(".\TestNorm1.txt")

      ' Define three versions of the same word. 
      Dim s1 As String = "sống"        ' create word with U+1ED1
      Dim s2 AS String = "s" + ChrW(&h00F4) + ChrW(&h0301) + "ng"
      Dim s3 As String = "so" + ChrW(&h0302) + ChrW(&h0301) + "ng"

      TestForEquality(s1, s2, s3)      
      sw.WriteLine()

      ' Normalize and compare strings using each normalization form.
      For Each formName In [Enum].GetNames(GetType(NormalizationForm))
         sw.WriteLine("Normalization {0}:", formName) 
         Dim nf As NormalizationForm = CType([Enum].Parse(GetType(NormalizationForm), formName),  
                                             NormalizationForm)
         Dim sn() As String = NormalizeStrings(nf, s1, s2, s3)
         TestForEquality(sn)           
         sw.WriteLine(vbCrLf)                                        
      Next
      
      sw.Close()   
   End Sub

   Private Sub TestForEquality(ParamArray words As String())
      For ctr As Integer = 0 To words.Length - 2
         For ctr2 As Integer = ctr + 1 To words.Length - 1 
            sw.WriteLine("{0} ({1}) = {2} ({3}): {4}", 
                         words(ctr), ShowBytes(words(ctr)),
                         words(ctr2), ShowBytes(words(ctr2)),
                         words(ctr).Equals(words(ctr2), StringComparison.Ordinal))
         Next                
      Next   
   End Sub

   Private Function ShowBytes(str As String) As String
      Dim result As String = Nothing
      For Each ch In str
         result += String.Format("{0} ", Convert.ToUInt16(ch).ToString("X4")) 
      Next
      Return result.Trim()            
   End Function  
   
   Private Function NormalizeStrings(nf As NormalizationForm, ParamArray words() As String) As String()
      For ctr As Integer = 0 To words.Length - 1
         If Not words(ctr).IsNormalized(nf) Then
            words(ctr) = words(ctr).Normalize(nf)
         End If    
      Next
      Return words   
   End Function
End Module
' The example displays the following output:
'       sống (0073 1ED1 006E 0067) = sống (0073 00F4 0301 006E 0067): False
'       sống (0073 1ED1 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
'       sống (0073 00F4 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): False
'       
'       Normalization FormC:
'       
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       
'       
'       Normalization FormD:
'       
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       
'       
'       Normalization FormKC:
'       
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       sống (0073 1ED1 006E 0067) = sống (0073 1ED1 006E 0067): True
'       
'       
'       Normalization FormKD:
'       
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True
'       sống (0073 006F 0302 0301 006E 0067) = sống (0073 006F 0302 0301 006E 0067): True

如需有關正規化和正規化表單的詳細資訊,請參閱System.Text.NormalizationForm,以及Unicode 標準附錄 #15:Unicode Normalization Forms正規化常見問題集unicode.org 網站上。For more information about normalization and normalization forms, see System.Text.NormalizationForm, as well as Unicode Standard Annex #15: Unicode Normalization Forms and the Normalization FAQ on the unicode.org website.

依類別目錄的字串作業String operations by category

String類別提供成員來比較測試字串是否相等,尋找的字元或在字串中,修改字串,擷取來自字串、 組合字串,格式化的值,複製字串的子字串的子字串的字串和正規化字串。The String class provides members for comparing strings, testing strings for equality, finding characters or substrings in a string, modifying a string, extracting substrings from a string, combining strings, formatting values, copying a string, and normalizing a string.

比較字串Comparing strings

您可以比較字串,以判斷兩者在排序次序中的相對位置,使用下列String方法:You can compare strings to determine their relative position in the sort order by using the following String methods:

  • Compare 傳回一個整數,表示要在排序次序中的第二個字串的一個字串的關聯性。Compare returns an integer that indicates the relationship of one string to a second string in the sort order.

  • CompareOrdinal 傳回一個整數,表示一個字串,以根據其字碼指標比較的第二個字串的關聯性。CompareOrdinal returns an integer that indicates the relationship of one string to a second string based on a comparison of their code points.

  • CompareTo 傳回一個整數,表示目前的字串執行個體在排序次序中的第二個字串的關聯性。CompareTo returns an integer that indicates the relationship of the current string instance to a second string in the sort order. CompareTo(String)方法會提供IComparableIComparable<T>實作String類別。The CompareTo(String) method provides the IComparable and IComparable<T> implementations for the String class.

測試字串相等Testing strings for equality

您呼叫Equals方法,以判斷兩個字串是否相等。You call the Equals method to determine whether two strings are equal. 執行個體Equals(String, String, StringComparison)和 靜態Equals(String, StringComparison)多載可讓您指定比較是否區分文化特性或序數,以及案例是考慮或忽略。The instance Equals(String, String, StringComparison) and the static Equals(String, StringComparison) overloads let you specify whether the comparison is culture-sensitive or ordinal, and whether case is considered or ignored. 大部分的測試相等為序數,並比較相等,以決定系統資源 (例如檔案系統物件) 的存取權應該一律是序數。Most tests for equality are ordinal, and comparisons for equality that determine access to a system resource (such as a file system object) should always be ordinal.

尋找字串中的字元Finding characters in a string

String類別包含兩種類型的搜尋方法:The String class includes two kinds of search methods:

警告

如果您想要搜尋特定的模式,而不是特定的子字串的字串,您應該使用規則運算式。If you want to search a string for a particular pattern rather than a specific substring, you should use regular expressions. 如需詳細資訊,請參閱 < .NET 規則運算式For more information, see .NET Regular Expressions.

修改字串Modifying a string

String類別包含下列方法看似修改字串的值:The String class includes the following methods that appear to modify the value of a string:

  • Insert 將字串插入至目前String執行個體。Insert inserts a string into the current String instance.

  • PadLeft 將指定之字元的一個或多個插入字串的開頭。PadLeft inserts one or more occurrences of a specified character at the beginning of a string.

  • PadRight 將指定之字元的一個或多個插入字串的結尾。PadRight inserts one or more occurrences of a specified character at the end of a string.

  • Remove 刪除從目前的子字串String執行個體。Remove deletes a substring from the current String instance.

  • Replace 使用在目前的另一個子字串取代子字串String執行個體。Replace replaces a substring with another substring in the current String instance.

  • ToLowerToLowerInvariant將字串中的所有字元都轉換成小寫。ToLower and ToLowerInvariant convert all the characters in a string to lowercase.

  • ToUpperToUpperInvariant字串中的所有字元都轉換成大寫。ToUpper and ToUpperInvariant convert all the characters in a string to uppercase.

  • Trim 移除開頭和結尾字串的所有出現的字元。Trim removes all occurrences of a character from the beginning and end of a string.

  • TrimEnd 從字串的結尾移除所有出現的字元。TrimEnd removes all occurrences of a character from the end of a string.

  • TrimStart 從移除所有出現的字元字串的開頭。TrimStart removes all occurrences of a character from the beginning of a string.

重要

字串修改的所有方法都會都傳回新String物件。All string modification methods return a new String object. 它們不會修改目前的執行個體的值。They don't modify the value of the current instance.

從字串擷取子字串Extracting substrings from a string

String.Split方法會將單一字串分隔成多個字串。The String.Split method separates a single string into multiple strings. 方法的多載可讓您指定多個分隔符號,來判斷擷取方法的子字串的最大數目,以及判斷空字串 (這就是相鄰的分隔符號時,就會發生) 是否包含在所傳回的字串。Overloads of the method allow you to specify multiple delimiters, to determine the maximum number of substrings that the method extracts, and to determine whether empty strings (which occur when delimiters are adjacent) are included among the returned strings.

結合字串Combining strings

下列String方法可用於字串串連:The following String methods can be used for string concatenation:

  • Concat 結合成單一字串的一或多個子字串。Concat combines one or more substrings into a single string.

  • Join 串連成單一元素的一或多個子字串,並將每一個子字串之間的分隔符號。Join concatenates one or more substrings into a single element and adds a separator between each substring.

格式化的值Formatting values

String.Format方法使用複合格式功能的某些物件或值的字串表示取代字串中的一或多個預留位置。The String.Format method uses the composite formatting feature to replace one or more placeholders in a string with the string representation of some object or value. Format方法通常用來執行下列動作:The Format method is often used to do the following:

  • 若要在字串中內嵌之數值的字串表示。To embed the string representation of a numeric value in a string.

  • 若要在字串中內嵌的日期和時間值的字串表示。To embed the string representation of a date and time value in a string.

  • 若要在字串中內嵌的列舉值的字串表示。To embed the string representation of an enumeration value in a string.

  • 若要內嵌支援某些物件的字串表示IFormattable字串中的介面。To embed the string representation of some object that supports the IFormattable interface in a string.

  • 若要靠右對齊或子字串在較大的字串內的欄位中靠左對齊。To right-justify or left-justify a substring in a field within a larger string.

如需格式化作業和範例的詳細資訊,請參閱Format多載摘要。For detailed information about formatting operations and examples, see the Format overload summary.

複製字串Copying a string

您可以呼叫下列String方法來建立一份字串:You can call the following String methods to make a copy of a string:

  • Clone 傳回參考現有String物件。Clone returns a reference to an existing String object.

  • Copy 建立一份現有的字串。Copy creates a copy of an existing string.

  • CopyTo 將字串的一部分複製到字元陣列。CopyTo copies a portion of a string to a character array.

正規化字串Normalizing a string

在 Unicode 中,單一字元可以有多個字碼指標。In Unicode, a single character can have multiple code points. 正規化會將這些對等的字元轉換成相同的二進位表示法。Normalization converts these equivalent characters into the same binary representation. String.Normalize方法會執行正規化和String.IsNormalized方法會判斷字串是否已標準化。The String.Normalize method performs the normalization, and the String.IsNormalized method determines whether a string is normalized.

如需詳細資訊和範例,請參閱 < 正規化稍早在本主題中的區段。For more information and an example, see the Normalization section earlier in this topic.

建構函式

String(Char*) String(Char*) String(Char*) String(Char*)

String 類別的新執行個體初始化為 Unicode 字元陣列的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters.

String(Char*, Int32, Int32) String(Char*, Int32, Int32) String(Char*, Int32, Int32) String(Char*, Int32, Int32)

String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置以及長度等等的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.

String(Char, Int32) String(Char, Int32) String(Char, Int32) String(Char, Int32)

String 類別的新執行個體初始化為由重複指定次數的指定 Unicode 字元所指示的值。Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.

String(Char[]) String(Char[]) String(Char[]) String(Char[])

String 類別的新執行個體初始化為 Unicode 字元陣列所指示的值。Initializes a new instance of the String class to the value indicated by an array of Unicode characters.

String(Char[], Int32, Int32) String(Char[], Int32, Int32) String(Char[], Int32, Int32) String(Char[], Int32, Int32)

String 類別的新執行個體初始化為 Unicode 字元陣列、在陣列內起始字元的位置和長度等等所指示的值。Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.

String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>) String(ReadOnlySpan<Char>)
String(SByte*) String(SByte*) String(SByte*) String(SByte*)

String 類別的新執行個體初始化為 8 位元帶正負號整數 (Signed Integer) 陣列的指標所指示的值。Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.

String(SByte*, Int32, Int32) String(SByte*, Int32, Int32) String(SByte*, Int32, Int32) String(SByte*, Int32, Int32)

String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置和長度的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length.

String(SByte*, Int32, Int32, Encoding) String(SByte*, Int32, Int32, Encoding) String(SByte*, Int32, Int32, Encoding) String(SByte*, Int32, Int32, Encoding)

String 類別的新執行個體初始化為 8 位元帶正負號整數的陣列、在該陣列內開始位置、長度和 Encoding 物件的指定指標所指示的值。Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

欄位

Empty Empty Empty Empty

表示空字串。Represents the empty string. 此欄位為唯讀。This field is read-only.

屬性

Chars[Index] Chars[Index] Chars[Index] Chars[Index]
Chars[Int32] Chars[Int32] Chars[Int32] Chars[Int32]

取得目前 Char 物件中指定位置的 String 物件。Gets the Char object at a specified position in the current String object.

Chars[Range] Chars[Range] Chars[Range] Chars[Range]
Length Length Length Length

取得目前 String 物件中字元的數目。Gets the number of characters in the current String object.

方法

Clone() Clone() Clone() Clone()

傳回對 String 這個執行個體的參考。Returns a reference to this instance of String.

Compare(String, Int32, String, Int32, Int32) Compare(String, Int32, String, Int32, Int32) Compare(String, Int32, String, Int32, Int32) Compare(String, Int32, String, Int32, Int32)

比較兩個指定的 String 物件子字串,並傳回一個整數,指出它們在排序順序中的相對位置。Compares substrings of two specified String objects and returns an integer that indicates their relative position in the sort order.

Compare(String, Int32, String, Int32, Int32, Boolean) Compare(String, Int32, String, Int32, Int32, Boolean) Compare(String, Int32, String, Int32, Int32, Boolean) Compare(String, Int32, String, Int32, Int32, Boolean)

比較兩個指定之 String 物件的子字串,忽略或區分兩者的大小寫,並傳回一個整數,表示兩者在排序順序中的相對位置。Compares substrings of two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo) Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)

比較兩個指定之 String 物件的子字串,忽略或區分兩者的大小寫,並使用文化特性資訊來影響比較,然後傳回一個整數,表示兩者在排序順序中的相對位置。Compares substrings of two specified String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)

比較兩個指定的 String 物件的子字串,使用指定的比較選項及特定文化特性資訊影響比較,然後傳回整數,這個整數表示這兩個子字串在排序次序中彼此的關聯性。Compares substrings of two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two substrings to each other in the sort order.

Compare(String, Int32, String, Int32, Int32, StringComparison) Compare(String, Int32, String, Int32, Int32, StringComparison) Compare(String, Int32, String, Int32, Int32, StringComparison) Compare(String, Int32, String, Int32, Int32, StringComparison)

使用指定的規則比較兩個指定之 String 物件的子字串,並傳回一個整數,表示兩者在排序順序中的相對位置。Compares substrings of two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

Compare(String, String) Compare(String, String) Compare(String, String) Compare(String, String)

比較兩個指定的 String 物件,並傳回一個整數,指出它們在排序順序中的相對位置。Compares two specified String objects and returns an integer that indicates their relative position in the sort order.

Compare(String, String, Boolean) Compare(String, String, Boolean) Compare(String, String, Boolean) Compare(String, String, Boolean)

比較兩個指定的 String 物件,忽略或區分兩者的大小寫,並傳回一個整數,表示兩者在排序順序中的相對位置。Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates their relative position in the sort order.

Compare(String, String, Boolean, CultureInfo) Compare(String, String, Boolean, CultureInfo) Compare(String, String, Boolean, CultureInfo) Compare(String, String, Boolean, CultureInfo)

比較兩個指定的 String 物件,忽略或區分兩者的大小寫,並使用特定文化特性資訊來影響比較,然後傳回一個整數,表示兩者在排序順序中的相對位置。Compares two specified String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position in the sort order.

Compare(String, String, CultureInfo, CompareOptions) Compare(String, String, CultureInfo, CompareOptions) Compare(String, String, CultureInfo, CompareOptions) Compare(String, String, CultureInfo, CompareOptions)

比較兩個指定的 String 物件,使用指定的比較選項及特定文化特性資訊影響比較,然後傳回整數,這個整數表示這兩個字串在排序次序中彼此的關聯性。Compares two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two strings to each other in the sort order.

Compare(String, String, StringComparison) Compare(String, String, StringComparison) Compare(String, String, StringComparison) Compare(String, String, StringComparison)

使用指定的規則比較兩個指定的 String 物件,並傳回一個整數,表示兩者在排序順序中的相對位置。Compares two specified String objects using the specified rules, and returns an integer that indicates their relative position in the sort order.

CompareOrdinal(String, Int32, String, Int32, Int32) CompareOrdinal(String, Int32, String, Int32, Int32) CompareOrdinal(String, Int32, String, Int32, Int32) CompareOrdinal(String, Int32, String, Int32, Int32)

藉由評估每個子字串中對應的 String 物件之數字值,比較兩個指定的 Char 物件之子字串。Compares substrings of two specified String objects by evaluating the numeric values of the corresponding Char objects in each substring.

CompareOrdinal(String, String) CompareOrdinal(String, String) CompareOrdinal(String, String) CompareOrdinal(String, String)

藉由評估每個字串中對應的 String 物件之數字值,比較兩個指定 Char 物件。Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string.

CompareTo(Object) CompareTo(Object) CompareTo(Object) CompareTo(Object)

比較這個執行個體與指定的 Object,並且指出這個執行個體在排序次序中,位於所指定 Object 之前、之後或相同位置。Compares this instance with a specified Object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.

CompareTo(String) CompareTo(String) CompareTo(String) CompareTo(String)

比較這個執行個體與指定的 String 物件,並且表示這個執行個體在排序次序中,位於所指定字串之前、之後或相同位置。Compares this instance with a specified String object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified string.

Concat(IEnumerable<String>) Concat(IEnumerable<String>) Concat(IEnumerable<String>) Concat(IEnumerable<String>)

串連類型 IEnumerable<T> 之已建構的 String 集合的成員。Concatenates the members of a constructed IEnumerable<T> collection of type String.

Concat(Object) Concat(Object) Concat(Object) Concat(Object)

建立指定之物件的字串表示。Creates the string representation of a specified object.

Concat(Object, Object) Concat(Object, Object) Concat(Object, Object) Concat(Object, Object)

串連兩個指定之物件的字串表示。Concatenates the string representations of two specified objects.

Concat(Object, Object, Object) Concat(Object, Object, Object) Concat(Object, Object, Object) Concat(Object, Object, Object)

串連三個指定之物件的字串表示。Concatenates the string representations of three specified objects.

Concat(Object, Object, Object, Object) Concat(Object, Object, Object, Object) Concat(Object, Object, Object, Object) Concat(Object, Object, Object, Object)

串連四個指定的物件之字串表示和選擇性變數長度參數清單中所指定的任何物件。Concatenates the string representations of four specified objects and any objects specified in an optional variable length parameter list.

Concat(Object[]) Concat(Object[]) Concat(Object[]) Concat(Object[])

串連指定之 Object 陣列中項目的字串表示法。Concatenates the string representations of the elements in a specified Object array.

Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>)
Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>)
Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>) Concat(ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>, ReadOnlySpan<Char>)
Concat(String, String) Concat(String, String) Concat(String, String) Concat(String, String)

串連 String 的兩個指定執行個體。Concatenates two specified instances of String.

Concat(String, String, String) Concat(String, String, String) Concat(String, String, String) Concat(String, String, String)

串連 String 的三個指定執行個體。Concatenates three specified instances of String.

Concat(String, String, String, String) Concat(String, String, String, String) Concat(String, String, String, String) Concat(String, String, String, String)

串連 String 的四個指定執行個體。Concatenates four specified instances of String.

Concat(String[]) Concat(String[]) Concat(String[]) Concat(String[])

串連指定 String 陣列中的項目。Concatenates the elements of a specified String array.

Concat<T>(IEnumerable<T>) Concat<T>(IEnumerable<T>) Concat<T>(IEnumerable<T>) Concat<T>(IEnumerable<T>)

串連 IEnumerable<T> 實作的成員。Concatenates the members of an IEnumerable<T> implementation.

Contains(Char) Contains(Char) Contains(Char) Contains(Char)
Contains(Char, StringComparison) Contains(Char, StringComparison) Contains(Char, StringComparison) Contains(Char, StringComparison)
Contains(String) Contains(String) Contains(String) Contains(String)

傳回值,這個值表示指定的子字串是否會出現在這個字串內。Returns a value indicating whether a specified substring occurs within this string.

Contains(String, StringComparison) Contains(String, StringComparison) Contains(String, StringComparison) Contains(String, StringComparison)
Copy(String) Copy(String) Copy(String) Copy(String)

使用與指定的 String 相同的值,建立 String 的新執行個體。Creates a new instance of String with the same value as a specified String.

CopyTo(Int32, Char[], Int32, Int32) CopyTo(Int32, Char[], Int32, Int32) CopyTo(Int32, Char[], Int32, Int32) CopyTo(Int32, Char[], Int32, Int32)

將字元的指定數目從這個執行個體的指定位置,複製到 Unicode 字元陣列的指定位置。Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.

Create<TState>(Int32, TState, SpanAction<Char,TState>) Create<TState>(Int32, TState, SpanAction<Char,TState>) Create<TState>(Int32, TState, SpanAction<Char,TState>) Create<TState>(Int32, TState, SpanAction<Char,TState>)
EndsWith(Char) EndsWith(Char) EndsWith(Char) EndsWith(Char)
EndsWith(String) EndsWith(String) EndsWith(String) EndsWith(String)

判斷這個字串執行個體的結尾是否符合指定的字串。Determines whether the end of this string instance matches the specified string.

EndsWith(String, Boolean, CultureInfo) EndsWith(String, Boolean, CultureInfo) EndsWith(String, Boolean, CultureInfo) EndsWith(String, Boolean, CultureInfo)

判斷當使用指定之文化特性進行比較時,這個字串執行個體的結尾是否符合指定的字串。Determines whether the end of this string instance matches the specified string when compared using the specified culture.

EndsWith(String, StringComparison) EndsWith(String, StringComparison) EndsWith(String, StringComparison) EndsWith(String, StringComparison)

判斷當使用指定的比較選項進行比較時,這個字串執行個體的結尾是否符合指定的字串。Determines whether the end of this string instance matches the specified string when compared using the specified comparison option.

EnumerateRunes() EnumerateRunes() EnumerateRunes() EnumerateRunes()
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷這個執行個體和指定的物件 (同時還必須是 String 物件) 是否具有相同的值。Determines whether this instance and a specified object, which must also be a String object, have the same value.

Equals(String) Equals(String) Equals(String) Equals(String)

判斷這個執行個體和另一個指定的 String 物件是否具有相同的值。Determines whether this instance and another specified String object have the same value.

Equals(String, String) Equals(String, String) Equals(String, String) Equals(String, String)

判斷兩個指定的 String 物件是否具有相同的值。Determines whether two specified String objects have the same value.

Equals(String, String, StringComparison) Equals(String, String, StringComparison) Equals(String, String, StringComparison) Equals(String, String, StringComparison)

判斷兩個指定的 String 物件是否具有相同的值。Determines whether two specified String objects have the same value. 參數可指定用於比較的文化特性、大小寫及排序規則。A parameter specifies the culture, case, and sort rules used in the comparison.

Equals(String, StringComparison) Equals(String, StringComparison) Equals(String, StringComparison) Equals(String, StringComparison)

判斷這個字串和指定的 String 物件是否具有相同的值。Determines whether this string and a specified String object have the same value. 參數可指定用於比較的文化特性、大小寫及排序規則。A parameter specifies the culture, case, and sort rules used in the comparison.

Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object) Format(IFormatProvider, String, Object)

以對應物件的字串表示,取代指定之字串中的一或多個格式項目。Replaces the format item or items in a specified string with the string representation of the corresponding object. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object) Format(IFormatProvider, String, Object, Object)

以兩個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of two specified objects. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object) Format(IFormatProvider, String, Object, Object, Object)

以三個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of three specified objects. 參數提供特定文化特性格式資訊。An parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[]) Format(IFormatProvider, String, Object[])

以指定陣列中對應物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representations of corresponding objects in a specified array. 參數提供特定文化特性格式資訊。A parameter supplies culture-specific formatting information.

Format(String, Object) Format(String, Object) Format(String, Object) Format(String, Object)

以指定物件的字串表示,取代字串中的一或多個格式項目。Replaces one or more format items in a string with the string representation of a specified object.

Format(String, Object, Object) Format(String, Object, Object) Format(String, Object, Object) Format(String, Object, Object)

以兩個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of two specified objects.

Format(String, Object, Object, Object) Format(String, Object, Object, Object) Format(String, Object, Object, Object) Format(String, Object, Object, Object)

以三個指定物件的字串表示,取代字串中的格式項目。Replaces the format items in a string with the string representation of three specified objects.

Format(String, Object[]) Format(String, Object[]) Format(String, Object[]) Format(String, Object[])

以指定陣列中對應物件的字串表示,取代指定之字串中的格式項目。Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

擷取可以逐一查看這個字串中個別字元的物件。Retrieves an object that can iterate through the individual characters in this string.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

傳回這個字串的雜湊碼。Returns the hash code for this string.

GetHashCode(ReadOnlySpan<Char>) GetHashCode(ReadOnlySpan<Char>) GetHashCode(ReadOnlySpan<Char>) GetHashCode(ReadOnlySpan<Char>)
GetHashCode(ReadOnlySpan<Char>, StringComparison) GetHashCode(ReadOnlySpan<Char>, StringComparison) GetHashCode(ReadOnlySpan<Char>, StringComparison) GetHashCode(ReadOnlySpan<Char>, StringComparison)
GetHashCode(StringComparison) GetHashCode(StringComparison) GetHashCode(StringComparison) GetHashCode(StringComparison)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
GetTypeCode() GetTypeCode() GetTypeCode() GetTypeCode()

傳回類別 TypeCodeStringReturns the TypeCode for class String.

IndexOf(Char) IndexOf(Char) IndexOf(Char) IndexOf(Char)

報告這個字串中指定之 Unicode 字元第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified Unicode character in this string.

IndexOf(Char, Int32) IndexOf(Char, Int32) IndexOf(Char, Int32) IndexOf(Char, Int32)

報告這個字串中指定之 Unicode 字元第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified Unicode character in this string. 搜尋從指定的字元位置開始。The search starts at a specified character position.

IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32)

報告這個執行個體中指定之字元第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified character in this instance. 搜尋從指定的字元位置開始,並檢視指定數目的字元位置。The search starts at a specified character position and examines a specified number of character positions.

IndexOf(Char, StringComparison) IndexOf(Char, StringComparison) IndexOf(Char, StringComparison) IndexOf(Char, StringComparison)

報告這個字串中指定之 Unicode 字元第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified Unicode character in this string. 參數會指定要用於指定字元的搜尋類型。A parameter specifies the type of search to use for the specified character.

IndexOf(String) IndexOf(String) IndexOf(String) IndexOf(String)

回報這個執行個體中指定之字串第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified string in this instance.

IndexOf(String, Int32) IndexOf(String, Int32) IndexOf(String, Int32) IndexOf(String, Int32)

回報這個執行個體中指定之字串第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified string in this instance. 搜尋從指定的字元位置開始。The search starts at a specified character position.

IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32)

回報這個執行個體中指定之字串第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified string in this instance. 搜尋從指定的字元位置開始,並檢視指定數目的字元位置。The search starts at a specified character position and examines a specified number of character positions.

IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison)

報告目前 String 物件中指定之字串第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified string in the current String object. 參數會指定目前字串中的開始搜尋位置、目前字串中要搜尋的字元數目,以及要用於指定字串的搜尋類型。Parameters specify the starting search position in the current string, the number of characters in the current string to search, and the type of search to use for the specified string.

IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison)

報告目前 String 物件中指定之字串第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified string in the current String object. 參數會指定目前字串中的開始搜尋位置和要用於指定字串的搜尋類型。Parameters specify the starting search position in the current string and the type of search to use for the specified string.

IndexOf(String, StringComparison) IndexOf(String, StringComparison) IndexOf(String, StringComparison) IndexOf(String, StringComparison)

報告目前 String 物件中指定之字串第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence of the specified string in the current String object. 參數會指定要用於指定字串的搜尋類型。A parameter specifies the type of search to use for the specified string.

IndexOfAny(Char[]) IndexOfAny(Char[]) IndexOfAny(Char[]) IndexOfAny(Char[])

報告指定的 Unicode 字元陣列中,任何字元在這個執行個體中第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.

IndexOfAny(Char[], Int32) IndexOfAny(Char[], Int32) IndexOfAny(Char[], Int32) IndexOfAny(Char[], Int32)

報告指定的 Unicode 字元陣列中,任何字元在這個執行個體中第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. 搜尋從指定的字元位置開始。The search starts at a specified character position.

IndexOfAny(Char[], Int32, Int32) IndexOfAny(Char[], Int32, Int32) IndexOfAny(Char[], Int32, Int32) IndexOfAny(Char[], Int32, Int32)

報告指定的 Unicode 字元陣列中,任何字元在這個執行個體中第一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. 搜尋從指定的字元位置開始,並檢視指定數目的字元位置。The search starts at a specified character position and examines a specified number of character positions.

Insert(Int32, String) Insert(Int32, String) Insert(Int32, String) Insert(Int32, String)

傳回新字串,其中已在這個執行個體中指定的索引位置插入指定的字串。Returns a new string in which a specified string is inserted at a specified index position in this instance.

Intern(String) Intern(String) Intern(String) Intern(String)

擷取指定的 String 的系統參考。Retrieves the system's reference to the specified String.

IsInterned(String) IsInterned(String) IsInterned(String) IsInterned(String)

擷取對指定 String 的參考。Retrieves a reference to a specified String.

IsNormalized() IsNormalized() IsNormalized() IsNormalized()

指出這個字串是否為 Unicode 正規化格式 C。Indicates whether this string is in Unicode normalization form C.

IsNormalized(NormalizationForm) IsNormalized(NormalizationForm) IsNormalized(NormalizationForm) IsNormalized(NormalizationForm)

指出這個字串是否為指定的 Unicode 正規化格式。Indicates whether this string is in the specified Unicode normalization form.

IsNullOrEmpty(String) IsNullOrEmpty(String) IsNullOrEmpty(String) IsNullOrEmpty(String)

表示指定的字串是否為 null 或空字串 ("")。Indicates whether the specified string is null or an empty string ("").

IsNullOrWhiteSpace(String) IsNullOrWhiteSpace(String) IsNullOrWhiteSpace(String) IsNullOrWhiteSpace(String)

表示指定的字串是否為 null、空白,或只由空白字元組成的字串。Indicates whether a specified string is null, empty, or consists only of white-space characters.

Join(Char, Object[]) Join(Char, Object[]) Join(Char, Object[]) Join(Char, Object[])
Join(Char, String[]) Join(Char, String[]) Join(Char, String[]) Join(Char, String[])
Join(Char, String[], Int32, Int32) Join(Char, String[], Int32, Int32) Join(Char, String[], Int32, Int32) Join(Char, String[], Int32, Int32)
Join(String, IEnumerable<String>) Join(String, IEnumerable<String>) Join(String, IEnumerable<String>) Join(String, IEnumerable<String>)

串連類型 IEnumerable<T> 之已建構的 String 集合的成員,並在每個成員之間使用指定的分隔符號。Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member.

Join(String, Object[]) Join(String, Object[]) Join(String, Object[]) Join(String, Object[])

串連物件陣列的項目,並在每個項目之間使用指定的分隔符號。Concatenates the elements of an object array, using the specified separator between each element.

Join(String, String[]) Join(String, String[]) Join(String, String[]) Join(String, String[])

串連字串陣列的所有項目,並在每個項目之間使用指定的分隔符號。Concatenates all the elements of a string array, using the specified separator between each element.

Join(String, String[], Int32, Int32) Join(String, String[], Int32, Int32) Join(String, String[], Int32, Int32) Join(String, String[], Int32, Int32)

串連字串陣列的指定項目,並在每個項目之間使用指定的分隔符號。Concatenates the specified elements of a string array, using the specified separator between each element.

Join<T>(Char, IEnumerable<T>) Join<T>(Char, IEnumerable<T>) Join<T>(Char, IEnumerable<T>) Join<T>(Char, IEnumerable<T>)
Join<T>(String, IEnumerable<T>) Join<T>(String, IEnumerable<T>) Join<T>(String, IEnumerable<T>) Join<T>(String, IEnumerable<T>)

串連集合的成員,並在每個成員之間使用指定的分隔符號。Concatenates the members of a collection, using the specified separator between each member.

LastIndexOf(Char) LastIndexOf(Char) LastIndexOf(Char) LastIndexOf(Char)

報告這個執行個體中指定之 Unicode 字元最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance.

LastIndexOf(Char, Int32) LastIndexOf(Char, Int32) LastIndexOf(Char, Int32) LastIndexOf(Char, Int32)

報告這個執行個體中指定之 Unicode 字元最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance. 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32)

報告這個執行個體的子字串中,指定的 Unicode 字元最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence of the specified Unicode character in a substring within this instance. 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

LastIndexOf(String) LastIndexOf(String) LastIndexOf(String) LastIndexOf(String)

回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence of a specified string within this instance.

LastIndexOf(String, Int32) LastIndexOf(String, Int32) LastIndexOf(String, Int32) LastIndexOf(String, Int32)

回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence of a specified string within this instance. 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32)

回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence of a specified string within this instance. 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison)

回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence of a specified string within this instance. 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。The search starts at a specified character position and proceeds backward toward the beginning of the string for the specified number of character positions. 參數會指定搜尋指定字串時要執行的比較類型。A parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison)

報告目前 String 物件中指定之字串最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the last occurrence of a specified string within the current String object. 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。The search starts at a specified character position and proceeds backward toward the beginning of the string. 參數會指定搜尋指定字串時要執行的比較類型。A parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison)

報告目前 String 物件中指定之字串最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index of the last occurrence of a specified string within the current String object. 參數會指定要用於指定字串的搜尋類型。A parameter specifies the type of search to use for the specified string.

LastIndexOfAny(Char[]) LastIndexOfAny(Char[]) LastIndexOfAny(Char[]) LastIndexOfAny(Char[])

報告 Unicode 陣列中的一或多個指定的字元,在這個執行個體中最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array.

LastIndexOfAny(Char[], Int32) LastIndexOfAny(Char[], Int32) LastIndexOfAny(Char[], Int32) LastIndexOfAny(Char[], Int32)

報告 Unicode 陣列中的一或多個指定的字元,在這個執行個體中最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOfAny(Char[], Int32, Int32) LastIndexOfAny(Char[], Int32, Int32) LastIndexOfAny(Char[], Int32, Int32) LastIndexOfAny(Char[], Int32, Int32)

報告 Unicode 陣列中的一或多個指定的字元,在這個執行個體中最後一次出現時的所在索引 (以零為起始)。Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
Normalize() Normalize() Normalize() Normalize()

傳回新的字串,其文字值與這個字串相同,但是其二進位表示為 Unicode 正規化格式 C。Returns a new string whose textual value is the same as this string, but whose binary representation is in Unicode normalization form C.

Normalize(NormalizationForm) Normalize(NormalizationForm) Normalize(NormalizationForm) Normalize(NormalizationForm)

傳回新的字串,其文字值與這個字串相同,但是其二進位表示為特定的 Unicode 正規化格式。Returns a new string whose textual value is the same as this string, but whose binary representation is in the specified Unicode normalization form.

PadLeft(Int32) PadLeft(Int32) PadLeft(Int32) PadLeft(Int32)

傳回新字串,此字串會以空格填補左側至指定的總長度,靠右對齊這個執行個體中的字元。Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length.

PadLeft(Int32, Char) PadLeft(Int32, Char) PadLeft(Int32, Char) PadLeft(Int32, Char)

傳回新字串,此字串會以指定的 Unicode 字元填補左側至指定的總長度,靠右對齊這個執行個體中的字元。Returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length.

PadRight(Int32) PadRight(Int32) PadRight(Int32) PadRight(Int32)

傳回新字串,此字串會以空格填補右側至指定的總長度,靠左對齊這個字串中的字元。Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.

PadRight(Int32, Char) PadRight(Int32, Char) PadRight(Int32, Char) PadRight(Int32, Char)

傳回新字串,此字串會以指定的 Unicode 字元填補右側至指定的總長度,靠左對齊這個字串中的字元。Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length.

Remove(Int32) Remove(Int32) Remove(Int32) Remove(Int32)

傳回新字串,其中已刪除目前執行個體中的所有字元 (從指定位置開始到最後一個位置為止)。Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.

Remove(Int32, Int32) Remove(Int32, Int32) Remove(Int32, Int32) Remove(Int32, Int32)

傳回新字串,其中已刪除在目前執行個體中指定位置開始之指定數目的字元。Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.

Replace(Char, Char) Replace(Char, Char) Replace(Char, Char) Replace(Char, Char)

傳回新字串,其中這個執行個體中所有出現的指定 Unicode 字元都取代成其他指定的 Unicode 字元。Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.

Replace(String, String) Replace(String, String) Replace(String, String) Replace(String, String)

傳回新字串,其中目前執行個體中所有出現的指定字串,都取代成其他指定的字串。Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

Replace(String, String, Boolean, CultureInfo) Replace(String, String, Boolean, CultureInfo) Replace(String, String, Boolean, CultureInfo) Replace(String, String, Boolean, CultureInfo)
Replace(String, String, StringComparison) Replace(String, String, StringComparison) Replace(String, String, StringComparison) Replace(String, String, StringComparison)
Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions) Split(Char, Int32, StringSplitOptions)
Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions) Split(Char, StringSplitOptions)
Split(Char[]) Split(Char[]) Split(Char[]) Split(Char[])

根據陣列中的字元分割字串成子字串。Splits a string into substrings that are based on the characters in an array.

Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32) Split(Char[], Int32)

根據陣列中的字元分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the characters in an array. 您也要指定傳回的子字串之最大數目。You also specify the maximum number of substrings to return.

Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions) Split(Char[], Int32, StringSplitOptions)

根據陣列中的字元分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the characters in an array.

Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions) Split(Char[], StringSplitOptions)

根據陣列中的字元分割字串成子字串。Splits a string into substrings based on the characters in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions) Split(String, Int32, StringSplitOptions)
Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions) Split(String, StringSplitOptions)
Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions) Split(String[], Int32, StringSplitOptions)

根據陣列中的字串分割字串成最大數目的子字串。Splits a string into a maximum number of substrings based on the strings in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions) Split(String[], StringSplitOptions)

根據陣列中的字串分割字串成子字串。Splits a string into substrings based on the strings in an array. 您可以指定子字串是否包含空的陣列元素。You can specify whether the substrings include empty array elements.

StartsWith(Char) StartsWith(Char) StartsWith(Char) StartsWith(Char)
StartsWith(String) StartsWith(String) StartsWith(String) StartsWith(String)

判斷這個字串執行個體的開頭是否符合指定的字串。Determines whether the beginning of this string instance matches the specified string.

StartsWith(String, Boolean, CultureInfo) StartsWith(String, Boolean, CultureInfo) StartsWith(String, Boolean, CultureInfo) StartsWith(String, Boolean, CultureInfo)

判斷當使用指定之文化特性進行比較時,這個字串執行個體的開頭是否符合指定的字串。Determines whether the beginning of this string instance matches the specified string when compared using the specified culture.

StartsWith(String, StringComparison) StartsWith(String, StringComparison) StartsWith(String, StringComparison) StartsWith(String, StringComparison)

判斷當使用指定之比較選項進行比較時,這個字串執行個體的開頭是否符合指定的字串。Determines whether the beginning of this string instance matches the specified string when compared using the specified comparison option.

Substring(Index) Substring(Index) Substring(Index) Substring(Index)
Substring(Int32) Substring(Int32) Substring(Int32) Substring(Int32)

從這個執行個體擷取子字串。Retrieves a substring from this instance. 子字串會在指定的字元位置開始並繼續到字串的結尾。The substring starts at a specified character position and continues to the end of the string.

Substring(Int32, Int32) Substring(Int32, Int32) Substring(Int32, Int32) Substring(Int32, Int32)

從這個執行個體擷取子字串。Retrieves a substring from this instance. 子字串起始於指定的字元位置,並且具有指定的長度。The substring starts at a specified character position and has a specified length.

Substring(Range) Substring(Range) Substring(Range) Substring(Range)
ToCharArray() ToCharArray() ToCharArray() ToCharArray()

將這個執行個體中的字元複製到 Unicode 字元陣列中。Copies the characters in this instance to a Unicode character array.

ToCharArray(Int32, Int32) ToCharArray(Int32, Int32) ToCharArray(Int32, Int32) ToCharArray(Int32, Int32)

將這個執行個體的指定子字串字元複製到 Unicode 字元陣列。Copies the characters in a specified substring in this instance to a Unicode character array.

ToLower() ToLower() ToLower() ToLower()

傳回此字串轉換為小寫的版本。Returns a copy of this string converted to lowercase.

ToLower(CultureInfo) ToLower(CultureInfo) ToLower(CultureInfo) ToLower(CultureInfo)

使用指定之文化特性的大小寫規則,傳回這個字串轉換成小寫的複本。Returns a copy of this string converted to lowercase, using the casing rules of the specified culture.

ToLowerInvariant() ToLowerInvariant() ToLowerInvariant() ToLowerInvariant()

使用不因文化特性而異的大小寫規則,傳回轉換成小寫的這個 String 物件之複本。Returns a copy of this String object converted to lowercase using the casing rules of the invariant culture.

ToString() ToString() ToString() ToString()

傳回這個 String 執行個體;不會實際執行轉換。Returns this instance of String; no actual conversion is performed.

ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider)

傳回這個 String 執行個體;不會實際執行轉換。Returns this instance of String; no actual conversion is performed.

ToUpper() ToUpper() ToUpper() ToUpper()

傳回此字串轉換為大寫的版本。Returns a copy of this string converted to uppercase.

ToUpper(CultureInfo) ToUpper(CultureInfo) ToUpper(CultureInfo) ToUpper(CultureInfo)

使用指定之文化特性的大小寫規則,傳回這個字串轉換成大寫的複本。Returns a copy of this string converted to uppercase, using the casing rules of the specified culture.

ToUpperInvariant() ToUpperInvariant() ToUpperInvariant() ToUpperInvariant()

使用不因文化特性而異的大小寫規則,傳回轉換成大寫的這個 String 物件之複本。Returns a copy of this String object converted to uppercase using the casing rules of the invariant culture.

Trim() Trim() Trim() Trim()

從目前的 String 物件中移除所有的開頭和結尾空白字元。Removes all leading and trailing white-space characters from the current String object.

Trim(Char) Trim(Char) Trim(Char) Trim(Char)
Trim(Char[]) Trim(Char[]) Trim(Char[]) Trim(Char[])

從目前的 String 物件中移除陣列中指定之一組字元的所有開頭和結尾指定項目。Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object.

TrimEnd() TrimEnd() TrimEnd() TrimEnd()
TrimEnd(Char) TrimEnd(Char) TrimEnd(Char) TrimEnd(Char)
TrimEnd(Char[]) TrimEnd(Char[]) TrimEnd(Char[]) TrimEnd(Char[])

從目前的 String 物件中移除陣列中指定之一組字元的所有結尾指定項目。Removes all trailing occurrences of a set of characters specified in an array from the current String object.

TrimStart() TrimStart() TrimStart() TrimStart()
TrimStart(Char) TrimStart(Char) TrimStart(Char) TrimStart(Char)
TrimStart(Char[]) TrimStart(Char[]) TrimStart(Char[]) TrimStart(Char[])

從目前的 String 物件中移除陣列中指定之一組字元的所有開頭指定項目。Removes all leading occurrences of a set of characters specified in an array from the current String object.

運算子

Equality(String, String) Equality(String, String) Equality(String, String) Equality(String, String)

判斷兩個指定的字串是否具有相同的值。Determines whether two specified strings have the same value.

Implicit(String to ReadOnlySpan<Char>) Implicit(String to ReadOnlySpan<Char>) Implicit(String to ReadOnlySpan<Char>) Implicit(String to ReadOnlySpan<Char>)
Inequality(String, String) Inequality(String, String) Inequality(String, String) Inequality(String, String)

判斷兩個指定的字串是否具有不同的值。Determines whether two specified strings have different values.

明確介面實作

IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object)
IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode()
IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider)

如需這個成員的說明,請參閱 ToBoolean(IFormatProvider)For a description of this member, see ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider)

如需這個成員的說明,請參閱 ToByte(IFormatProvider)For a description of this member, see ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider)

如需這個成員的說明,請參閱 ToChar(IFormatProvider)For a description of this member, see ToChar(IFormatProvider).

IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider)

如需這個成員的說明,請參閱 ToDateTime(IFormatProvider)For a description of this member, see ToDateTime(IFormatProvider).

IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider)

如需這個成員的說明,請參閱 ToDecimal(IFormatProvider)For a description of this member, see ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider)

如需這個成員的說明,請參閱 ToDouble(IFormatProvider)For a description of this member, see ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToInt16(IFormatProvider)For a description of this member, see ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToInt32(IFormatProvider)For a description of this member, see ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToInt64(IFormatProvider)For a description of this member, see ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider)

如需這個成員的說明,請參閱 ToSByte(IFormatProvider)For a description of this member, see ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider)

如需這個成員的說明,請參閱 ToSingle(IFormatProvider)For a description of this member, see ToSingle(IFormatProvider).

IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider)
IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider)

如需這個成員的說明,請參閱 ToType(Type, IFormatProvider)For a description of this member, see ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt16(IFormatProvider)For a description of this member, see ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt32(IFormatProvider)For a description of this member, see ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt64(IFormatProvider)For a description of this member, see ToUInt64(IFormatProvider).

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

傳回列舉值,可逐一查看目前的 String 物件。Returns an enumerator that iterates through the current String object.

IEnumerable<Char>.GetEnumerator() IEnumerable<Char>.GetEnumerator() IEnumerable<Char>.GetEnumerator() IEnumerable<Char>.GetEnumerator()

傳回列舉值,可逐一查看目前的 String 物件。Returns an enumerator that iterates through the current String object.

Extension Methods

ToImmutableArray<TSource>(IEnumerable<TSource>) ToImmutableArray<TSource>(IEnumerable<TSource>) ToImmutableArray<TSource>(IEnumerable<TSource>) ToImmutableArray<TSource>(IEnumerable<TSource>)

從指定的集合建立不可變的陣列。Creates an immutable array from the specified collection.

ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

從現有的項目集合建構不可變的字典,將轉換函式套用至來源索引鍵。Constructs an immutable dictionary from an existing collection of elements, applying a transformation function to the source keys.

ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>) ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>) ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>) ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據序列的某些轉換來建構不可變的字典。Constructs an immutable dictionary based on some transformation of a sequence.

ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)

列舉索引鍵/值組的序列,並產生其內容的不可變字典。Enumerates a sequence of key/value pairs and produces an immutable dictionary of its contents.

ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)

列舉索引鍵/值組的序列,並使用指定的索引鍵比較子產生不可變的排序字典作為內容。Enumerates a sequence of key/value pairs and produces an immutable dictionary of its contents by using the specified key comparer.

ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>, IEqualityComparer<TValue>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>, IEqualityComparer<TValue>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>, IEqualityComparer<TValue>) ToImmutableDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>, IEqualityComparer<TValue>)

列舉索引鍵/值組的序列,並使用指定的索引鍵與值比較子產生其內容的不可變字典。Enumerates a sequence of key/value pairs and produces an immutable dictionary of its contents by using the specified key and value comparers.

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>)

列舉及轉換序列,並產生其內容的不可變字典。Enumerates and transforms a sequence, and produces an immutable dictionary of its contents.

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>)

列舉及轉換序列,並使用指定的索引鍵比較子產生其內容的不可變字典。Enumerates and transforms a sequence, and produces an immutable dictionary of its contents by using the specified key comparer.

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>, IEqualityComparer<TValue>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>, IEqualityComparer<TValue>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>, IEqualityComparer<TValue>) ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>, IEqualityComparer<TValue>)

列舉及轉換序列,並使用指定的索引鍵與值比較子產生其內容的不可變字典。Enumerates and transforms a sequence, and produces an immutable dictionary of its contents by using the specified key and value comparers.

ToImmutableHashSet<TSource>(IEnumerable<TSource>) ToImmutableHashSet<TSource>(IEnumerable<TSource>) ToImmutableHashSet<TSource>(IEnumerable<TSource>) ToImmutableHashSet<TSource>(IEnumerable<TSource>)

列舉序列,並產生其內容之不可變雜湊集。Enumerates a sequence and produces an immutable hash set of its contents.

ToImmutableHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) ToImmutableHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) ToImmutableHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) ToImmutableHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

列舉序列、產生其內容之不可變雜湊集,且針對集合類型使用指定的相等比較子。Enumerates a sequence, produces an immutable hash set of its contents, and uses the specified equality comparer for the set type.

ToImmutableList<TSource>(IEnumerable<TSource>) ToImmutableList<TSource>(IEnumerable<TSource>) ToImmutableList<TSource>(IEnumerable<TSource>) ToImmutableList<TSource>(IEnumerable<TSource>)

列舉序列,並產生其內容的不可變清單。Enumerates a sequence and produces an immutable list of its contents.

ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)

列舉索引鍵/值組的序列,並產生不可變的排序字典作為內容。Enumerates a sequence of key/value pairs and produces an immutable sorted dictionary of its contents.

ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IComparer<TKey>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IComparer<TKey>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IComparer<TKey>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IComparer<TKey>)

列舉索引鍵/值組的序列,並使用指定的索引鍵比較子產生不可變的排序字典作為內容。Enumerates a sequence of key/value pairs and produces an immutable dictionary of its contents by using the specified key comparer.

ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IComparer<TKey>, IEqualityComparer<TValue>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IComparer<TKey>, IEqualityComparer<TValue>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IComparer<TKey>, IEqualityComparer<TValue>) ToImmutableSortedDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IComparer<TKey>, IEqualityComparer<TValue>)

列舉索引鍵/值組的序列,並使用指定的索引鍵與值比較子產生不可變的排序字典作為內容。Enumerates a sequence of key/value pairs and produces an immutable sorted dictionary of its contents by using the specified key and value comparers.

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>)

列舉及轉換序列,並產生不可變的排序字典作為內容。Enumerates and transforms a sequence, and produces an immutable sorted dictionary of its contents.

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>)

列舉及轉換序列,並使用指定的索引鍵比較子產生不可變的排序字典作為內容。Enumerates and transforms a sequence, and produces an immutable sorted dictionary of its contents by using the specified key comparer.

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>, IEqualityComparer<TValue>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>, IEqualityComparer<TValue>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>, IEqualityComparer<TValue>) ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>, IEqualityComparer<TValue>)

列舉及轉換序列,並使用指定的索引鍵與值比較子產生不可變的排序字典作為內容。Enumerates and transforms a sequence, and produces an immutable sorted dictionary of its contents by using the specified key and value comparers.

ToImmutableSortedSet<TSource>(IEnumerable<TSource>) ToImmutableSortedSet<TSource>(IEnumerable<TSource>) ToImmutableSortedSet<TSource>(IEnumerable<TSource>) ToImmutableSortedSet<TSource>(IEnumerable<TSource>)

列舉序列,並產生其內容的不可變排序資料集。Enumerates a sequence and produces an immutable sorted set of its contents.

ToImmutableSortedSet<TSource>(IEnumerable<TSource>, IComparer<TSource>) ToImmutableSortedSet<TSource>(IEnumerable<TSource>, IComparer<TSource>) ToImmutableSortedSet<TSource>(IEnumerable<TSource>, IComparer<TSource>) ToImmutableSortedSet<TSource>(IEnumerable<TSource>, IComparer<TSource>)

列舉序列、產生其內容的不可變排序資料集,並使用指定的比較子。Enumerates a sequence, produces an immutable sorted set of its contents, and uses the specified comparer.

CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>)

根據輸入 DataTable 物件 (其中泛型參數 TDataRow) 傳回包含 IEnumerable<T> 物件複本的 DataRowReturns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 IEnumerable<T> 物件複製到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 IEnumerable<T> 物件複製到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)

將累加函式套用到序列上。Applies an accumulator function over a sequence.

Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)

將累加函式套用到序列上。Applies an accumulator function over a sequence. 使用指定的初始值做為初始累加值。The specified seed value is used as the initial accumulator value.

Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>) Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>)

將累加函式套用到序列上。Applies an accumulator function over a sequence. 使用指定的值做為初始累加值,並使用指定的函式來選取結果值。The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value.

All<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) All<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) All<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) All<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

判斷序列的所有項目是否全都符合條件。Determines whether all elements of a sequence satisfy a condition.

Any<TSource>(IEnumerable<TSource>) Any<TSource>(IEnumerable<TSource>) Any<TSource>(IEnumerable<TSource>) Any<TSource>(IEnumerable<TSource>)

判斷序列是否包含任何項目。Determines whether a sequence contains any elements.

Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

判斷序列的任何項目是否符合條件。Determines whether any element of a sequence satisfies a condition.

Append<TSource>(IEnumerable<TSource>, TSource) Append<TSource>(IEnumerable<TSource>, TSource) Append<TSource>(IEnumerable<TSource>, TSource) Append<TSource>(IEnumerable<TSource>, TSource)

將值附加在序列結尾。Appends a value to the end of the sequence.

AsEnumerable<TSource>(IEnumerable<TSource>) AsEnumerable<TSource>(IEnumerable<TSource>) AsEnumerable<TSource>(IEnumerable<TSource>) AsEnumerable<TSource>(IEnumerable<TSource>)

傳回 IEnumerable<T> 類型的輸入。Returns the input typed as IEnumerable<T>.

Average(IEnumerable<Decimal>) Average(IEnumerable<Decimal>) Average(IEnumerable<Decimal>) Average(IEnumerable<Decimal>)

計算 Decimal 值序列的平均值。Computes the average of a sequence of Decimal values.

Average(IEnumerable<Double>) Average(IEnumerable<Double>) Average(IEnumerable<Double>) Average(IEnumerable<Double>)

計算 Double 值序列的平均值。Computes the average of a sequence of Double values.

Average(IEnumerable<Int32>) Average(IEnumerable<Int32>) Average(IEnumerable<Int32>) Average(IEnumerable<Int32>)

計算 Int32 值序列的平均值。Computes the average of a sequence of Int32 values.

Average(IEnumerable<Int64>) Average(IEnumerable<Int64>) Average(IEnumerable<Int64>) Average(IEnumerable<Int64>)

計算 Int64 值序列的平均值。Computes the average of a sequence of Int64 values.

Average(IEnumerable<Nullable<Decimal>>) Average(IEnumerable<Nullable<Decimal>>) Average(IEnumerable<Nullable<Decimal>>) Average(IEnumerable<Nullable<Decimal>>)

計算可為 Null 之 Decimal 值序列的平均值。Computes the average of a sequence of nullable Decimal values.

Average(IEnumerable<Nullable<Double>>) Average(IEnumerable<Nullable<Double>>) Average(IEnumerable<Nullable<Double>>) Average(IEnumerable<Nullable<Double>>)

計算可為 Null 之 Double 值序列的平均值。Computes the average of a sequence of nullable Double values.

Average(IEnumerable<Nullable<Int32>>) Average(IEnumerable<Nullable<Int32>>) Average(IEnumerable<Nullable<Int32>>) Average(IEnumerable<Nullable<Int32>>)

計算可為 Null 之 Int32 值序列的平均值。Computes the average of a sequence of nullable Int32 values.

Average(IEnumerable<Nullable<Int64>>) Average(IEnumerable<Nullable<Int64>>) Average(IEnumerable<Nullable<Int64>>) Average(IEnumerable<Nullable<Int64>>)

計算可為 Null 之 Int64 值序列的平均值。Computes the average of a sequence of nullable Int64 values.

Average(IEnumerable<Nullable<Single>>) Average(IEnumerable<Nullable<Single>>) Average(IEnumerable<Nullable<Single>>) Average(IEnumerable<Nullable<Single>>)

計算可為 Null 之 Single 值序列的平均值。Computes the average of a sequence of nullable Single values.

Average(IEnumerable<Single>) Average(IEnumerable<Single>) Average(IEnumerable<Single>) Average(IEnumerable<Single>)

計算 Single 值序列的平均值。Computes the average of a sequence of Single values.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Decimal 值序列的平均值。Computes the average of a sequence of Decimal values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Double 值序列的平均值。Computes the average of a sequence of Double values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Int32 值序列的平均值。Computes the average of a sequence of Int32 values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Int64 值序列的平均值。Computes the average of a sequence of Int64 values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Decimal 值的平均值。Computes the average of a sequence of nullable Decimal values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Double 值的平均值。Computes the average of a sequence of nullable Double values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Int32 值的平均值。Computes the average of a sequence of nullable Int32 values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Int64 值的平均值。Computes the average of a sequence of nullable Int64 values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Single 值的平均值。Computes the average of a sequence of nullable Single values that are obtained by invoking a transform function on each element of the input sequence.

Average<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Average<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Single 值序列的平均值。Computes the average of a sequence of Single values that are obtained by invoking a transform function on each element of the input sequence.

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

串連兩個序列。Concatenates two sequences.

Contains<TSource>(IEnumerable<TSource>, TSource) Contains<TSource>(IEnumerable<TSource>, TSource) Contains<TSource>(IEnumerable<TSource>, TSource) Contains<TSource>(IEnumerable<TSource>, TSource)

使用預設的相等比較子 (Comparer) 來判斷序列是否包含指定的項目。Determines whether a sequence contains a specified element by using the default equality comparer.

Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>) Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>) Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>) Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來判斷序列是否包含指定的項目。Determines whether a sequence contains a specified element by using a specified IEqualityComparer<T>.

Count<TSource>(IEnumerable<TSource>) Count<TSource>(IEnumerable<TSource>) Count<TSource>(IEnumerable<TSource>) Count<TSource>(IEnumerable<TSource>)

傳回序列中的項目數。Returns the number of elements in a sequence.

Count<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Count<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Count<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Count<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回數字,代表指定之序列中符合條件的項目數目。Returns a number that represents how many elements in the specified sequence satisfy a condition.

DefaultIfEmpty<TSource>(IEnumerable<TSource>) DefaultIfEmpty<TSource>(IEnumerable<TSource>) DefaultIfEmpty<TSource>(IEnumerable<TSource>) DefaultIfEmpty<TSource>(IEnumerable<TSource>)

傳回指定之序列的項目;如果序列是空的,則傳回單一集合中型別參數的預設值。Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.

DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)

傳回指定之序列的項目;如果序列是空的,則傳回單一集合中型別參數的預設值。Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

Distinct<TSource>(IEnumerable<TSource>) Distinct<TSource>(IEnumerable<TSource>) Distinct<TSource>(IEnumerable<TSource>) Distinct<TSource>(IEnumerable<TSource>)

使用預設的相等比較子來比較值,以便從序列傳回獨特的項目。Returns distinct elements from a sequence by using the default equality comparer to compare values.

Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,以便從序列傳回獨特的項目。Returns distinct elements from a sequence by using a specified IEqualityComparer<T> to compare values.

ElementAt<TSource>(IEnumerable<TSource>, Int32) ElementAt<TSource>(IEnumerable<TSource>, Int32) ElementAt<TSource>(IEnumerable<TSource>, Int32) ElementAt<TSource>(IEnumerable<TSource>, Int32)

傳回位於序列中指定索引處的項目。Returns the element at a specified index in a sequence.

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32) ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32) ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32) ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32)

傳回位於序列中指定索引處的元素;如果索引超出範圍,則傳回預設值。Returns the element at a specified index in a sequence or a default value if the index is out of range.

Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用預設相等比較子來比較值,以便產生兩個序列的差異。Produces the set difference of two sequences by using the default equality comparer to compare values.

Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,以便產生兩個序列的差異。Produces the set difference of two sequences by using the specified IEqualityComparer<T> to compare values.

First<TSource>(IEnumerable<TSource>) First<TSource>(IEnumerable<TSource>) First<TSource>(IEnumerable<TSource>) First<TSource>(IEnumerable<TSource>)

傳回序列的第一個項目。Returns the first element of a sequence.

First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定條件的第一個元素。Returns the first element in a sequence that satisfies a specified condition.

FirstOrDefault<TSource>(IEnumerable<TSource>) FirstOrDefault<TSource>(IEnumerable<TSource>) FirstOrDefault<TSource>(IEnumerable<TSource>) FirstOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的第一個元素;如果序列中沒有包含任何元素,則傳回預設值。Returns the first element of a sequence, or a default value if the sequence contains no elements.

FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合條件的第一個元素;如果找不到這類元素,則傳回預設值。Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.

GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

依據指定的索引鍵選擇器函式來群組序列的項目。Groups the elements of a sequence according to a specified key selector function.

GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>) GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>) GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>) GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

依據指定的索引鍵選取器函式來群組序列的項目,並使用指定的比較子來比較索引鍵。Groups the elements of a sequence according to a specified key selector function and compares the keys by using a specified comparer.

GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>) GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>) GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>) GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>)

依據指定的索引鍵選取器函式來群組序列的項目,並使用指定的函式來投影每個群組的項目。Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.

GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

依據索引鍵選取器函式來群組序列中的項目。Groups the elements of a sequence according to a key selector function. 索引鍵是使用比較子來進行比較,而每個群組的項目都是利用指定的函式進行投影。The keys are compared by using a comparer and each group's elements are projected by using a specified function.

GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>) GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>) GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>) GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>)

依據指定的索引鍵選取器函式來群組序列的項目,並從每個群組及其索引鍵建立結果值。Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key.

GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>, IEqualityComparer<TKey>)

依據指定的索引鍵選取器函式來群組序列的項目,並從每個群組及其索引鍵建立結果值。Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. 索引鍵是使用指定的比較子來進行比較。The keys are compared by using a specified comparer.

GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>) GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>) GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>) GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>)

依據指定的索引鍵選取器函式來群組序列的項目,並從每個群組及其索引鍵建立結果值。Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. 每個群組的項目都是利用指定的函式進行投影。The elements of each group are projected by using a specified function.

GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>, IEqualityComparer<TKey>) GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>, IEqualityComparer<TKey>)

依據指定的索引鍵選取器函式來群組序列的項目,並從每個群組及其索引鍵建立結果值。Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. 索引鍵值是使用指定的比較子來進行比較,而每個群組的項目則都是利用指定的函式進行投影。Key values are compared by using a specified comparer, and the elements of each group are projected by using a specified function.

GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>,TResult>) GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>,TResult>) GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>,TResult>) GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>,TResult>)

根據索引鍵相等與否,將兩個序列的項目相互關聯,並群組產生的結果。Correlates the elements of two sequences based on equality of keys and groups the results. 預設的相等比較子是用於比較索引鍵。The default equality comparer is used to compare keys.

GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>,TResult>, IEqualityComparer<TKey>) GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>,TResult>, IEqualityComparer<TKey>) GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>,TResult>, IEqualityComparer<TKey>) GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>,TResult>, IEqualityComparer<TKey>)

根據索引鍵相等與否,將兩個序列的項目相互關聯,並群組產生的結果。Correlates the elements of two sequences based on key equality and groups the results. 指定的 IEqualityComparer<T> 是用於比較索引鍵。A specified IEqualityComparer<T> is used to compare keys.

Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用預設相等比較子來比較值,以便產生兩個序列的交集。Produces the set intersection of two sequences by using the default equality comparer to compare values.

Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,以便產生兩個序列的交集。Produces the set intersection of two sequences by using the specified IEqualityComparer<T> to compare values.

Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>) Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>) Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>) Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>)

根據相符索引鍵,將兩個序列的項目相互關聯。Correlates the elements of two sequences based on matching keys. 預設的相等比較子是用於比較索引鍵。The default equality comparer is used to compare keys.

Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>) Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>) Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>) Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>)

根據相符索引鍵,將兩個序列的項目相互關聯。Correlates the elements of two sequences based on matching keys. 指定的 IEqualityComparer<T> 是用於比較索引鍵。A specified IEqualityComparer<T> is used to compare keys.

Last<TSource>(IEnumerable<TSource>) Last<TSource>(IEnumerable<TSource>) Last<TSource>(IEnumerable<TSource>) Last<TSource>(IEnumerable<TSource>)

傳回序列的最後一個項目。Returns the last element of a sequence.

Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定之條件的最後一個元素。Returns the last element of a sequence that satisfies a specified condition.

LastOrDefault<TSource>(IEnumerable<TSource>) LastOrDefault<TSource>(IEnumerable<TSource>) LastOrDefault<TSource>(IEnumerable<TSource>) LastOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的最後一個元素;如果序列中沒有包含任何元素,則傳回預設值。Returns the last element of a sequence, or a default value if the sequence contains no elements.

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合條件的最後一個元素;如果找不到這類元素,則傳回預設值。Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.

LongCount<TSource>(IEnumerable<TSource>) LongCount<TSource>(IEnumerable<TSource>) LongCount<TSource>(IEnumerable<TSource>) LongCount<TSource>(IEnumerable<TSource>)

傳回代表序列中項目總數的 Int64Returns an Int64 that represents the total number of elements in a sequence.

LongCount<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) LongCount<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) LongCount<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) LongCount<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回 Int64,其代表序列中符合條件的項目數目。Returns an Int64 that represents how many elements in a sequence satisfy a condition.

Max(IEnumerable<Decimal>) Max(IEnumerable<Decimal>) Max(IEnumerable<Decimal>) Max(IEnumerable<Decimal>)

傳回 Decimal 值序列中的最大值。Returns the maximum value in a sequence of Decimal values.

Max(IEnumerable<Double>) Max(IEnumerable<Double>) Max(IEnumerable<Double>) Max(IEnumerable<Double>)

傳回 Double 值序列中的最大值。Returns the maximum value in a sequence of Double values.

Max(IEnumerable<Int32>) Max(IEnumerable<Int32>) Max(IEnumerable<Int32>) Max(IEnumerable<Int32>)

傳回 Int32 值序列中的最大值。Returns the maximum value in a sequence of Int32 values.

Max(IEnumerable<Int64>) Max(IEnumerable<Int64>) Max(IEnumerable<Int64>) Max(IEnumerable<Int64>)

傳回 Int64 值序列中的最大值。Returns the maximum value in a sequence of Int64 values.

Max(IEnumerable<Nullable<Decimal>>) Max(IEnumerable<Nullable<Decimal>>) Max(IEnumerable<Nullable<Decimal>>) Max(IEnumerable<Nullable<Decimal>>)

傳回可為 Null 之 Decimal 值序列中的最大值。Returns the maximum value in a sequence of nullable Decimal values.

Max(IEnumerable<Nullable<Double>>) Max(IEnumerable<Nullable<Double>>) Max(IEnumerable<Nullable<Double>>) Max(IEnumerable<Nullable<Double>>)

傳回可為 Null 之 Double 值序列中的最大值。Returns the maximum value in a sequence of nullable Double values.

Max(IEnumerable<Nullable<Int32>>) Max(IEnumerable<Nullable<Int32>>) Max(IEnumerable<Nullable<Int32>>) Max(IEnumerable<Nullable<Int32>>)

傳回可為 Null 之 Int32 值序列中的最大值。Returns the maximum value in a sequence of nullable Int32 values.

Max(IEnumerable<Nullable<Int64>>) Max(IEnumerable<Nullable<Int64>>) Max(IEnumerable<Nullable<Int64>>) Max(IEnumerable<Nullable<Int64>>)

傳回可為 Null 之 Int64 值序列中的最大值。Returns the maximum value in a sequence of nullable Int64 values.

Max(IEnumerable<Nullable<Single>>) Max(IEnumerable<Nullable<Single>>) Max(IEnumerable<Nullable<Single>>) Max(IEnumerable<Nullable<Single>>)

傳回可為 Null 之 Single 值序列中的最大值。Returns the maximum value in a sequence of nullable Single values.

Max(IEnumerable<Single>) Max(IEnumerable<Single>) Max(IEnumerable<Single>) Max(IEnumerable<Single>)

傳回 Single 值序列中的最大值。Returns the maximum value in a sequence of Single values.

Max<TSource>(IEnumerable<TSource>) Max<TSource>(IEnumerable<TSource>) Max<TSource>(IEnumerable<TSource>) Max<TSource>(IEnumerable<TSource>)

傳回泛型序列中的最大值。Returns the maximum value in a generic sequence.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Decimal 值。Invokes a transform function on each element of a sequence and returns the maximum Decimal value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Double 值。Invokes a transform function on each element of a sequence and returns the maximum Double value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Int32 值。Invokes a transform function on each element of a sequence and returns the maximum Int32 value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Int64 值。Invokes a transform function on each element of a sequence and returns the maximum Int64 value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Decimal 值。Invokes a transform function on each element of a sequence and returns the maximum nullable Decimal value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Double 值。Invokes a transform function on each element of a sequence and returns the maximum nullable Double value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Int32 值。Invokes a transform function on each element of a sequence and returns the maximum nullable Int32 value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Int64 值。Invokes a transform function on each element of a sequence and returns the maximum nullable Int64 value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Single 值。Invokes a transform function on each element of a sequence and returns the maximum nullable Single value.

Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Single 值。Invokes a transform function on each element of a sequence and returns the maximum Single value.

Max<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Max<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Max<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Max<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

在泛型序列的每個項目上叫用轉換函式,並傳回最大的結果值。Invokes a transform function on each element of a generic sequence and returns the maximum resulting value.

Min(IEnumerable<Decimal>) Min(IEnumerable<Decimal>) Min(IEnumerable<Decimal>) Min(IEnumerable<Decimal>)

傳回 Decimal 值序列中的最小值。Returns the minimum value in a sequence of Decimal values.

Min(IEnumerable<Double>) Min(IEnumerable<Double>) Min(IEnumerable<Double>) Min(IEnumerable<Double>)

傳回 Double 值序列中的最小值。Returns the minimum value in a sequence of Double values.

Min(IEnumerable<Int32>) Min(IEnumerable<Int32>) Min(IEnumerable<Int32>) Min(IEnumerable<Int32>)

傳回 Int32 值序列中的最小值。Returns the minimum value in a sequence of Int32 values.

Min(IEnumerable<Int64>) Min(IEnumerable<Int64>) Min(IEnumerable<Int64>) Min(IEnumerable<Int64>)

傳回 Int64 值序列中的最小值。Returns the minimum value in a sequence of Int64 values.

Min(IEnumerable<Nullable<Decimal>>) Min(IEnumerable<Nullable<Decimal>>) Min(IEnumerable<Nullable<Decimal>>) Min(IEnumerable<Nullable<Decimal>>)

傳回可為 Null 之 Decimal 值序列中的最小值。Returns the minimum value in a sequence of nullable Decimal values.

Min(IEnumerable<Nullable<Double>>) Min(IEnumerable<Nullable<Double>>) Min(IEnumerable<Nullable<Double>>) Min(IEnumerable<Nullable<Double>>)

傳回可為 Null 之 Double 值序列中的最小值。Returns the minimum value in a sequence of nullable Double values.

Min(IEnumerable<Nullable<Int32>>) Min(IEnumerable<Nullable<Int32>>) Min(IEnumerable<Nullable<Int32>>) Min(IEnumerable<Nullable<Int32>>)

傳回可為 Null 之 Int32 值序列中的最小值。Returns the minimum value in a sequence of nullable Int32 values.

Min(IEnumerable<Nullable<Int64>>) Min(IEnumerable<Nullable<Int64>>) Min(IEnumerable<Nullable<Int64>>) Min(IEnumerable<Nullable<Int64>>)

傳回可為 Null 之 Int64 值序列中的最小值。Returns the minimum value in a sequence of nullable Int64 values.

Min(IEnumerable<Nullable<Single>>) Min(IEnumerable<Nullable<Single>>) Min(IEnumerable<Nullable<Single>>) Min(IEnumerable<Nullable<Single>>)

傳回可為 Null 之 Single 值序列中的最小值。Returns the minimum value in a sequence of nullable Single values.

Min(IEnumerable<Single>) Min(IEnumerable<Single>) Min(IEnumerable<Single>) Min(IEnumerable<Single>)

傳回 Single 值序列中的最小值。Returns the minimum value in a sequence of Single values.

Min<TSource>(IEnumerable<TSource>) Min<TSource>(IEnumerable<TSource>) Min<TSource>(IEnumerable<TSource>) Min<TSource>(IEnumerable<TSource>)

傳回泛型序列中的最小值。Returns the minimum value in a generic sequence.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Decimal 值。Invokes a transform function on each element of a sequence and returns the minimum Decimal value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Double 值。Invokes a transform function on each element of a sequence and returns the minimum Double value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Int32>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Int32 值。Invokes a transform function on each element of a sequence and returns the minimum Int32 value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Int64>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Int64 值。Invokes a transform function on each element of a sequence and returns the minimum Int64 value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Decimal 值。Invokes a transform function on each element of a sequence and returns the minimum nullable Decimal value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Double 值。Invokes a transform function on each element of a sequence and returns the minimum nullable Double value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Int32 值。Invokes a transform function on each element of a sequence and returns the minimum nullable Int32 value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Int64 值。Invokes a transform function on each element of a sequence and returns the minimum nullable Int64 value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Single 值。Invokes a transform function on each element of a sequence and returns the minimum nullable Single value.

Min<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Single>) Min<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Single 值。Invokes a transform function on each element of a sequence and returns the minimum Single value.

Min<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Min<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Min<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Min<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

在泛型序列的每個項目上叫用轉換函式,並傳回最小的結果值。Invokes a transform function on each element of a generic sequence and returns the minimum resulting value.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

依據索引鍵,按遞增順序排序序列中的項目。Sorts the elements of a sequence in ascending order according to a key.

OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

使用指定的比較子,依遞增順序排序序列中的項目。Sorts the elements of a sequence in ascending order by using a specified comparer.

OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

依據索引鍵,按遞減順序排序序列中的項目。Sorts the elements of a sequence in descending order according to a key.

OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

使用指定的比較子,依遞減順序排序序列中的項目。Sorts the elements of a sequence in descending order by using a specified comparer.

Prepend<TSource>(IEnumerable<TSource>, TSource) Prepend<TSource>(IEnumerable<TSource>, TSource) Prepend<TSource>(IEnumerable<TSource>, TSource) Prepend<TSource>(IEnumerable<TSource>, TSource)

將值新增至序列的開頭。Adds a value to the beginning of the sequence.

Reverse<TSource>(IEnumerable<TSource>) Reverse<TSource>(IEnumerable<TSource>) Reverse<TSource>(IEnumerable<TSource>) Reverse<TSource>(IEnumerable<TSource>)

反轉序列中項目的排序方向。Inverts the order of the elements in a sequence.

Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

將序列的每個元素規劃成一個新的表單。Projects each element of a sequence into a new form.

Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>) Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>) Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>) Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>)

透過加入項目的索引,將序列的每個項目投影成新的表單。Projects each element of a sequence into a new form by incorporating the element's index.

SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>) SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>)

將序列的每個項目都投影成 IEnumerable<T>,並將產生的序列簡化成單一序列。Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.

SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>)

將序列的每個項目都投影成 IEnumerable<T>,並將產生的序列簡化成單一序列。Projects each element of a sequence to an IEnumerable<T>, and flattens the resulting sequences into one sequence. 各來源項目的索引是在該項目的投影表單中使用。The index of each source element is used in the projected form of that element.

SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)

將序列的每個項目投影為 IEnumerable<T>、將產生的序列簡化成單一序列,並對其中的每個項目叫用結果選取器函式。Projects each element of a sequence to an IEnumerable<T>, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein.

SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>) SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)

將序列的每個項目投影為 IEnumerable<T>、將產生的序列簡化成單一序列,並對其中的每個項目叫用結果選取器函式。Projects each element of a sequence to an IEnumerable<T>, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein. 各來源項目的索引是在該項目的中繼投影表單中使用。The index of each source element is used in the intermediate projected form of that element.

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用項目之型別的預設相等比較子來比較項目,以判斷兩個序列是否相等。Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較項目,以判斷兩個序列是否相等。Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer<T>.

Single<TSource>(IEnumerable<TSource>) Single<TSource>(IEnumerable<TSource>) Single<TSource>(IEnumerable<TSource>) Single<TSource>(IEnumerable<TSource>)

傳回序列的唯一一個元素,如果序列中不是正好一個元素,則擲回例外狀況。Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定之條件的唯一一個元素,如果有一個以上這類元素,則擲回例外狀況。Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.

SingleOrDefault<TSource>(IEnumerable<TSource>) SingleOrDefault<TSource>(IEnumerable<TSource>) SingleOrDefault<TSource>(IEnumerable<TSource>) SingleOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的唯一一個項目,如果序列是空白,則為預設值,如果序列中有一個以上的項目,這個方法就會擲回例外狀況。Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定之條件的唯一一個元素,如果沒有這類元素,則為預設值,如果有一個以上的元素符合條件,這個方法就會擲回例外狀況。Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.

Skip<TSource>(IEnumerable<TSource>, Int32) Skip<TSource>(IEnumerable<TSource>, Int32) Skip<TSource>(IEnumerable<TSource>, Int32) Skip<TSource>(IEnumerable<TSource>, Int32)

略過序列中指定的項目數目,然後傳回其餘項目。Bypasses a specified number of elements in a sequence and then returns the remaining elements.

SkipLast<TSource>(IEnumerable<TSource>, Int32) SkipLast<TSource>(IEnumerable<TSource>, Int32) SkipLast<TSource>(IEnumerable<TSource>, Int32) SkipLast<TSource>(IEnumerable<TSource>, Int32)
SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

只要指定的條件為 true,便略過序列中的項目,然後傳回其餘項目。Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.

SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

只要指定的條件為 true,便略過序列中的項目,然後傳回其餘項目。Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. 項目的索引是用於述詞功能的邏輯中。The element's index is used in the logic of the predicate function.

Sum(IEnumerable<Decimal>) Sum(IEnumerable<Decimal>) Sum(IEnumerable<Decimal>) Sum(IEnumerable<Decimal>)

計算 Decimal 值序列的總和。Computes the sum of a sequence of Decimal values.

Sum(IEnumerable<Double>) Sum(IEnumerable<Double>) Sum(IEnumerable<Double>) Sum(IEnumerable<Double>)

計算 Double 值序列的總和。Computes the sum of a sequence of Double values.

Sum(IEnumerable<Int32>) Sum(IEnumerable<Int32>) Sum(IEnumerable<Int32>) Sum(IEnumerable<Int32>)

計算 Int32 值序列的總和。Computes the sum of a sequence of Int32 values.

Sum(IEnumerable<Int64>) Sum(IEnumerable<Int64>) Sum(IEnumerable<Int64>) Sum(IEnumerable<Int64>)

計算 Int64 值序列的總和。Computes the sum of a sequence of Int64 values.

Sum(IEnumerable<Nullable<Decimal>>) Sum(IEnumerable<Nullable<Decimal>>) Sum(IEnumerable<Nullable<Decimal>>) Sum(IEnumerable<Nullable<Decimal>>)

計算可為 Null 之 Decimal 值序列的總和。Computes the sum of a sequence of nullable Decimal values.

Sum(IEnumerable<Nullable<Double>>) Sum(IEnumerable<Nullable<Double>>) Sum(IEnumerable<Nullable<Double>>) Sum(IEnumerable<Nullable<Double>>)

計算可為 Null 之 Double 值序列的總和。Computes the sum of a sequence of nullable Double values.

Sum(IEnumerable<Nullable<Int32>>) Sum(IEnumerable<Nullable<Int32>>) Sum(IEnumerable<Nullable<Int32>>) Sum(IEnumerable<Nullable<Int32>>)

計算可為 Null 之 Int32 值序列的總和。Computes the sum of a sequence of nullable Int32 values.

Sum(IEnumerable<Nullable<Int64>>) Sum(IEnumerable<Nullable<Int64>>) Sum(IEnumerable<Nullable<Int64>>) Sum(IEnumerable<Nullable<Int64>>)

計算可為 Null 之 Int64 值序列的總和。Computes the sum of a sequence of nullable Int64 values.

Sum(IEnumerable<Nullable<Single>>) Sum(IEnumerable<Nullable<Single>>) Sum(IEnumerable<Nullable<Single>>) Sum(IEnumerable<Nullable<Single>>)

計算可為 Null 之 Single 值序列的總和。Computes the sum of a sequence of nullable Single values.

Sum(IEnumerable<Single>) Sum(IEnumerable<Single>) Sum(IEnumerable<Single>) Sum(IEnumerable<Single>)

計算 Single 值序列的總和。Computes the sum of a sequence of Single values.

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Sum<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Sum<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) Sum<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Decimal 值序列的總和。Computes the sum of the sequence of Decimal values that are obtained by invoking a transform function on each element of the input sequence.

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Sum<TSource>(IEnumerable<TSource>, Func<TSource,Double>) Sum<TSource>(IEnumerable<TSource>, Func<TSource,Double>)