通过


String.Join 方法

定义

使用每个元素或成员之间的指定分隔符连接指定数组的元素或集合的成员。

重载

名称 说明
Join(String, String[], Int32, Int32)

使用每个元素之间的指定分隔符连接字符串数组的指定元素。

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

连接字符串数组,使用每个成员之间的指定分隔符,从位于startIndex位置的元素value开始,并连接到count元素。

Join(String, String[])

使用每个元素之间的指定分隔符连接字符串数组的所有元素。

Join(String, ReadOnlySpan<String>)

使用每个成员之间的指定分隔符连接字符串范围。

Join(String, ReadOnlySpan<Object>)

使用每个成员之间的指定分隔符连接对象范围的字符串表示形式。

Join(Char, ReadOnlySpan<String>)

使用每个成员之间的指定分隔符连接字符串范围。

Join(String, IEnumerable<String>)

使用每个成员之间的指定分隔符连接类型String构造IEnumerable<T>集合的成员。

Join(Char, String[])

使用每个成员之间的指定分隔符连接字符串数组。

Join(String, Object[])

使用每个元素之间的指定分隔符连接对象数组的元素。

Join(Char, ReadOnlySpan<Object>)

使用每个成员之间的指定分隔符连接对象范围的字符串表示形式。

Join(Char, Object[])

使用每个成员之间的指定分隔符连接对象数组的字符串表示形式。

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

使用每个成员之间的指定分隔符连接集合的成员。

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

使用每个成员之间的指定分隔符连接集合的成员。

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

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

使用每个元素之间的指定分隔符连接字符串数组的指定元素。

public:
 static System::String ^ Join(System::String ^ separator, cli::array <System::String ^> ^ value, int startIndex, int count);
public static string Join(string separator, string[] value, int startIndex, int count);
public static string Join(string? separator, string?[] value, int startIndex, int count);
static member Join : string * string[] * int * int -> string
Public Shared Function Join (separator As String, value As String(), startIndex As Integer, count As Integer) As String

参数

separator
String

要用作分隔符的字符串。 separator 仅当包含多个元素时 value ,才会包含在返回的字符串中。

value
String[]

包含要连接的元素的数组。

startIndex
Int32

要使用的第一个元素 value

count
Int32

要使用的元素 value 数。

返回

一个字符串,由count以字符分隔开头startIndexvalueseparator元素组成。

-或-

Empty 如果 count 为零,则为零。

例外

valuenull

startIndexcount 小于 0。

-或-

startIndexcount 号大于 . 中的 value元素数。

内存不足。

示例

以下示例连接水果名称数组中的两个元素。

String[] val = {"apple", "orange", "grape", "pear"};
String sep   = ", ";
String result;

Console.WriteLine("sep = '{0}'", sep);
Console.WriteLine("val[] = {{'{0}' '{1}' '{2}' '{3}'}}", val[0], val[1], val[2], val[3]);
result = String.Join(sep, val, 1, 2);
Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result);

// This example produces the following results:
// sep = ', '
// val[] = {'apple' 'orange' 'grape' 'pear'}
// String.Join(sep, val, 1, 2) = 'orange, grape'
open System

let vals = [| "apple"; "orange"; "grape"; "pear" |]
let sep   = ", "

printfn $"sep = '{sep}'"
printfn $"vals[] = {{'{vals[0]}' '{vals[1]}' '{vals[2]}' '{vals[3]}'}}"
let result = String.Join(sep, vals, 1, 2)
printfn $"String.Join(sep, vals, 1, 2) = '{result}'"

// This example produces the following results:
// sep = ', '
// vals[] = {'apple' 'orange' 'grape' 'pear'}
// String.Join(sep, vals, 1, 2) = 'orange, grape'
Class Sample
   Public Shared Sub Main()
      Dim val As [String]() =  {"apple", "orange", "grape", "pear"}
      Dim sep As [String] = ", "
      Dim result As [String]

      Console.WriteLine("sep = '{0}'", sep)
      Console.WriteLine("val() = {{'{0}' '{1}' '{2}' '{3}'}}", val(0), val(1), val(2), val(3))
      result = [String].Join(sep, val, 1, 2)
      Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result)
   End Sub
End Class

'This example displays the following output:
'       sep = ', '
'       val() = {'apple' 'orange' 'grape' 'pear'}
'       String.Join(sep, val, 1, 2) = 'orange, grape'

注解

例如,如果 separator 为“, 且元素 value 为”apple“、”orange“、”grape“和”pear“, Join(separator, value, 1, 2) 则返回”orange, grape”。

null如果是separator,则改用空字符串(String.Empty)。 如果存在valuenull任何元素,则改用空字符串。

另请参阅

适用于

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

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

连接字符串数组,使用每个成员之间的指定分隔符,从位于startIndex位置的元素value开始,并连接到count元素。

public:
 static System::String ^ Join(char separator, cli::array <System::String ^> ^ value, int startIndex, int count);
public static string Join(char separator, string?[] value, int startIndex, int count);
public static string Join(char separator, string[] value, int startIndex, int count);
static member Join : char * string[] * int * int -> string
Public Shared Function Join (separator As Char, value As String(), startIndex As Integer, count As Integer) As String

参数

separator
Char

使用每个成员之间的指定分隔符连接字符串数组,从位于指定索引处的元素开始,包括指定数量的元素。

value
String[]

要连接的字符串数组。

startIndex
Int32

要连接的第一项 value

count
Int32

value 连接的元素数,从位置中的 startIndex 元素开始。

返回

一个字符串,由count以字符分隔开头startIndexvalueseparator元素组成。

-或-

Empty 如果 count 为零,则为零。

例外

valuenull

startIndexcount 为负数。

-或-

startIndex 大于长度 value - count

生成的字符串的长度溢出允许的最大长度(Int32.MaxValue)。

适用于

Join(String, String[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

使用每个元素之间的指定分隔符连接字符串数组的所有元素。

public:
 static System::String ^ Join(System::String ^ separator, ... cli::array <System::String ^> ^ value);
public:
 static System::String ^ Join(System::String ^ separator, cli::array <System::String ^> ^ value);
public static string Join(string separator, params string[] value);
public static string Join(string? separator, params string?[] value);
public static string Join(string separator, string[] value);
static member Join : string * string[] -> string
Public Shared Function Join (separator As String, ParamArray value As String()) As String
Public Shared Function Join (separator As String, value As String()) As String

参数

separator
String

要用作分隔符的字符串。 separator 仅当包含多个元素时 value ,才会包含在返回的字符串中。

value
String[]

包含要连接的元素的数组。

返回

由字符串分隔separatorvalue元素组成的字符串。

-或-

Empty 如果有 value 零个元素。

例外

valuenull

生成的字符串的长度溢出允许的最大长度(Int32.MaxValue)。

示例

以下示例演示了该方法 Join

using System;

public class JoinTest
{
    public static void Main()
    {
        Console.WriteLine(MakeLine(0, 5, ", "));
        Console.WriteLine(MakeLine(1, 6, "  "));
        Console.WriteLine(MakeLine(9, 9, ": "));
        Console.WriteLine(MakeLine(4, 7, "< "));
    }

    private static string MakeLine(int initVal, int multVal, string sep)
    {
        string [] sArr = new string [10];

        for (int i = initVal; i < initVal + 10; i++)
            sArr[i - initVal] = String.Format("{0,-3}", i * multVal);

        return String.Join(sep, sArr);
    }
}
// The example displays the following output:
//       0  , 5  , 10 , 15 , 20 , 25 , 30 , 35 , 40 , 45
//       6    12   18   24   30   36   42   48   54   60
//       81 : 90 : 99 : 108: 117: 126: 135: 144: 153: 162
//       28 < 35 < 42 < 49 < 56 < 63 < 70 < 77 < 84 < 91
open System

let makeLine initVal multVal (sep: string) =
    let sArr = Array.zeroCreate<string> 10 

    for i = initVal to initVal + 9 do
        sArr[i - initVal] <- String.Format("{0,-3}", i * multVal)

    String.Join(sep, sArr)

printfn $"""{makeLine 0 5 ", "}"""
printfn $"""{makeLine 1 6 "  "}"""
printfn $"""{makeLine 9 9 ": "}"""
printfn $"""{makeLine 4 7 "< "}"""

// The example displays the following output:
//       0  , 5  , 10 , 15 , 20 , 25 , 30 , 35 , 40 , 45
//       6    12   18   24   30   36   42   48   54   60
//       81 : 90 : 99 : 108: 117: 126: 135: 144: 153: 162
//       28 < 35 < 42 < 49 < 56 < 63 < 70 < 77 < 84 < 91
Public Class JoinTest
    
    Public Shared Sub Main()
        
        Console.WriteLine(MakeLine(0, 5, ", "))
        Console.WriteLine(MakeLine(1, 6, "  "))
        Console.WriteLine(MakeLine(9, 9, ": "))
        Console.WriteLine(MakeLine(4, 7, "< "))
    End Sub
    
    
    Private Shared Function MakeLine(initVal As Integer, multVal As Integer, sep As String) As String
        Dim sArr(10) As String
        Dim i As Integer
        
        
        For i = initVal To (initVal + 10) - 1
            sArr((i - initVal)) = [String].Format("{0,-3}", i * multVal)
        
        Next i
        Return [String].Join(sep, sArr)
    End Function 'MakeLine
End Class
' The example displays the following output:
'       0  , 5  , 10 , 15 , 20 , 25 , 30 , 35 , 40 , 45
'       6    12   18   24   30   36   42   48   54   60
'       81 : 90 : 99 : 108: 117: 126: 135: 144: 153: 162
'       28 < 35 < 42 < 49 < 56 < 63 < 70 < 77 < 84 < 91

注解

例如,如果 separator 为“, 且元素 value 为”apple“、”orange“、”grape“和”pear“, Join(separator, value) 则返回”apple、orange、grape、pear”。

null如果是separator,则改用空字符串(String.Empty)。 如果存在valuenull任何元素,则改用空字符串。

另请参阅

适用于

Join(String, ReadOnlySpan<String>)

Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接字符串范围。

public:
 static System::String ^ Join(System::String ^ separator, ReadOnlySpan<System::String ^> value);
public static string Join(string? separator, scoped ReadOnlySpan<string?> value);
static member Join : string * ReadOnlySpan<string> -> string
Public Shared Function Join (separator As String, value As ReadOnlySpan(Of String)) As String

参数

separator
String

要用作分隔符的字符串。 separator 仅当包含多个元素时 value ,才会包含在返回的字符串中。

value
ReadOnlySpan<String>

包含要连接的元素的跨度。

返回

由字符串分隔separatorvalue元素组成的字符串。 -或 - Empty 如果有 value 零个元素。

适用于

Join(String, ReadOnlySpan<Object>)

Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接对象范围的字符串表示形式。

public:
 static System::String ^ Join(System::String ^ separator, ReadOnlySpan<System::Object ^> values);
public static string Join(string? separator, scoped ReadOnlySpan<object?> values);
static member Join : string * ReadOnlySpan<obj> -> string
Public Shared Function Join (separator As String, values As ReadOnlySpan(Of Object)) As String

参数

separator
String

要用作分隔符的字符串。 separator 仅当包含多个元素时 values ,才会包含在返回的字符串中。

values
ReadOnlySpan<Object>

将串联其字符串表示形式的对象的范围。

返回

由字符串分隔separatorvalues元素组成的字符串。 -或 - Empty 如果有 values 零个元素。

适用于

Join(Char, ReadOnlySpan<String>)

Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接字符串范围。

public:
 static System::String ^ Join(char separator, ReadOnlySpan<System::String ^> value);
public static string Join(char separator, scoped ReadOnlySpan<string?> value);
static member Join : char * ReadOnlySpan<string> -> string
Public Shared Function Join (separator As Char, value As ReadOnlySpan(Of String)) As String

参数

separator
Char

要用作分隔符的字符。 separator 仅当包含多个元素时 value ,才会包含在返回的字符串中。

value
ReadOnlySpan<String>

包含要连接的元素的跨度。

返回

由字符串分隔separatorvalue元素组成的字符串。 -或 - Empty 如果有 value 零个元素。

适用于

Join(String, IEnumerable<String>)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接类型String构造IEnumerable<T>集合的成员。

public:
 static System::String ^ Join(System::String ^ separator, System::Collections::Generic::IEnumerable<System::String ^> ^ values);
public static string Join(string separator, System.Collections.Generic.IEnumerable<string> values);
public static string Join(string? separator, System.Collections.Generic.IEnumerable<string?> values);
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join(string separator, System.Collections.Generic.IEnumerable<string> values);
static member Join : string * seq<string> -> string
[<System.Runtime.InteropServices.ComVisible(false)>]
static member Join : string * seq<string> -> string
Public Shared Function Join (separator As String, values As IEnumerable(Of String)) As String

参数

separator
String

要用作分隔符的字符串。 separator 仅当包含多个元素时 values ,才会包含在返回的字符串中。

values
IEnumerable<String>

包含要连接的字符串的集合。

返回

由字符串分隔separatorvalues元素组成的字符串。

-或-

Empty 如果有 values 零个元素。

属性

例外

valuesnull

生成的字符串的长度溢出允许的最大长度(Int32.MaxValue)。

示例

以下示例使用 Eratosthenes 算法的 Sieve 计算小于或等于 100 的质数。 它将结果分配给 List<T> 类型 String对象,然后 Join(String, IEnumerable<String>) 传递给该方法。

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      int maxPrime = 100;
      List<int> primes = GetPrimes(maxPrime);
      Console.WriteLine("Primes less than {0}:", maxPrime);
      Console.WriteLine("   {0}", String.Join(" ", primes));
   }

   private static List<int> GetPrimes(int maxPrime)
   {
      Array values = Array.CreateInstance(typeof(int), 
                              new int[] { maxPrime - 1}, new int[] { 2 });
      // Use Sieve of Eratosthenes to determine prime numbers.
      for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
      {
                           
         if ((int) values.GetValue(ctr) == 1) continue;
         
         for (int multiplier = ctr; multiplier <=  maxPrime / 2; multiplier++)
            if (ctr * multiplier <= maxPrime)
               values.SetValue(1, ctr * multiplier);
      }      
      
      List<int> primes = new List<int>();
      for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
         if ((int) values.GetValue(ctr) == 0) 
            primes.Add(ctr);
      return primes;
   }   
}
// The example displays the following output:
//    Primes less than 100:
//       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
open System

let getPrimes maxPrime =
    let values = Array.CreateInstance(typeof<int>, [| maxPrime - 1 |], [| 2 |])
    // Use Sieve of Eratosthenes to determine prime numbers.
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 |> float |> sqrt |> ceil |> int do
        if values.GetValue i :?> int <> 1 then
            for multiplier = i to maxPrime / 2 do
                if i * multiplier <= maxPrime then
                    values.SetValue(1, i * multiplier)

    let primes = ResizeArray()
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
        if values.GetValue i :?> int = 0 then
            primes.Add i
    primes

let maxPrime = 100
let primes = getPrimes maxPrime
printfn $"Primes less than {maxPrime}:"
printfn $"""   {String.Join(" ", primes)}"""

// The example displays the following output:
//    Primes less than 100:
//       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim maxPrime As Integer = 100
      Dim primes As List(Of String) = GetPrimes(maxPrime)
      Console.WriteLine("Primes less than {0}:", maxPrime)
      Console.WriteLine("   {0}", String.Join(" ", primes))
   End Sub

   Private Function GetPrimes(maxPrime As Integer) As List(Of String)
      Dim values As Array = Array.CreateInstance(GetType(Integer), _
                              New Integer() { maxPrime - 1}, New Integer(){ 2 })
        ' Use Sieve of Eratosthenes to determine prime numbers.
      For ctr As Integer = values.GetLowerBound(0) To _
                           CInt(Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))))
         If CInt(values.GetValue(ctr)) = 1 Then Continue For

         For multiplier As Integer = ctr To maxPrime \ 2
            If ctr * multiplier <= maxPrime Then values.SetValue(1, ctr * multiplier)
         Next
      Next

      Dim primes As New List(Of String)
      For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
         If CInt(values.GetValue(ctr)) = 0 Then primes.Add(ctr.ToString())
      Next
      Return primes
   End Function
End Module

' The example displays the following output:
'    Primes less than 100:
'       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

注解

null如果是separator,则改用空字符串(String.Empty)。 如果任一成员valuesnull,则改用空字符串。

Join(String, IEnumerable<String>) 是一种方便的方法,可用于连接集合中的每个元素, IEnumerable(Of String) 而无需先将元素转换为字符串数组。 它特别适用于 Language-Integrated 查询(LINQ)查询表达式。 以下示例将包含字母大写或小写字母的对象传递给 List(Of String) lambda 表达式,该表达式选择等于或大于特定字母的字母(在本示例中为“M”)。 IEnumerable(Of String)该方法返回Enumerable.Where的集合将传递给Join(String, IEnumerable<String>)方法,以将结果显示为单个字符串。

using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
   public static void Main()
   {
      string output = String.Join(" ", GetAlphabet(true).Where( letter => 
                      letter.CompareTo("M") >= 0));
      Console.WriteLine(output);  
   }

   private static List<string> GetAlphabet(bool upper)
   {
      List<string> alphabet = new List<string>();
      int charValue = upper ? 65 : 97;
      for (int ctr = 0; ctr <= 25; ctr++)
         alphabet.Add(((char)(charValue + ctr)).ToString());
      return alphabet; 
   }
}
// The example displays the following output:
//      M N O P Q R S T U V W X Y Z
// This F# example uses Seq.filter instead of Linq.
open System

let getAlphabet upper =
    let charValue = if upper then 65 else 97
    seq {
        for i = 0 to 25 do
            charValue + i
            |> char
            |> string
    }

String.Join(" ", getAlphabet true |> Seq.filter (fun letter -> letter.CompareTo "M" >= 0))
|> printfn "%s"

// The example displays the following output:
//      M N O P Q R S T U V W X Y Z
Imports System.Collections.Generic
Imports System.Linq

Module modMain
   Public Sub Main()
      Dim output As String = String.Join(" ", GetAlphabet(True).Where(Function(letter) _
                                                         letter >= "M"))

      Console.WriteLine(output)
   End Sub

   Private Function GetAlphabet(upper As Boolean) As List(Of String)
      Dim alphabet As New List(Of String)
      Dim charValue As Integer = CInt(IIf(upper, 65, 97))
      For ctr As Integer = 0 To 25
         alphabet.Add(ChrW(charValue + ctr).ToString())
      Next
      Return alphabet
   End Function
End Module

' The example displays the following output:
'      M N O P Q R S T U V W X Y Z

另请参阅

适用于

Join(Char, String[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接字符串数组。

public:
 static System::String ^ Join(char separator, ... cli::array <System::String ^> ^ value);
public static string Join(char separator, params string?[] value);
public static string Join(char separator, params string[] value);
static member Join : char * string[] -> string
Public Shared Function Join (separator As Char, ParamArray value As String()) As String

参数

separator
Char

要用作分隔符的字符。 separator 仅当包含多个元素时 value ,才会包含在返回的字符串中。

value
String[]

要连接的字符串数组。

返回

由字符分隔separatorvalue元素组成的字符串。

-或-

Empty 如果有 value 零个元素。

例外

valuenull

生成的字符串的长度溢出允许的最大长度(Int32.MaxValue)。

适用于

Join(String, Object[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

使用每个元素之间的指定分隔符连接对象数组的元素。

public:
 static System::String ^ Join(System::String ^ separator, ... cli::array <System::Object ^> ^ values);
public static string Join(string separator, params object[] values);
public static string Join(string? separator, params object?[] values);
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join(string separator, params object[] values);
static member Join : string * obj[] -> string
[<System.Runtime.InteropServices.ComVisible(false)>]
static member Join : string * obj[] -> string
Public Shared Function Join (separator As String, ParamArray values As Object()) As String

参数

separator
String

要用作分隔符的字符串。 separator 仅当包含多个元素时 values ,才会包含在返回的字符串中。

values
Object[]

包含要连接的元素的数组。

返回

由字符串分隔separatorvalues元素组成的字符串。

-或-

Empty 如果有 values 零个元素。

-或-

仅 .NET Framework:Empty如果第一个元素为 nullvalues .

属性

例外

valuesnull

生成的字符串的长度溢出允许的最大长度(Int32.MaxValue)。

示例

以下示例使用 Eratosthenes 算法的 Sieve 计算小于或等于 100 的质数。 它将结果分配给整数数组,然后传递给 Join(String, Object[]) 该方法。

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      int maxPrime = 100;
      int[] primes = GetPrimes(maxPrime);
      Console.WriteLine("Primes less than {0}:", maxPrime);
      Console.WriteLine("   {0}", String.Join(" ", primes));
   }

   private static int[] GetPrimes(int maxPrime)
   {
      Array values = Array.CreateInstance(typeof(int), 
                              new int[] { maxPrime - 1}, new int[] { 2 }); 
      // Use Sieve of Eratosthenes to determine prime numbers.
      for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
      {
                           
         if ((int) values.GetValue(ctr) == 1) continue;
         
         for (int multiplier = ctr; multiplier <=  maxPrime / 2; multiplier++)
            if (ctr * multiplier <= maxPrime)
               values.SetValue(1, ctr * multiplier);
      }      
      
      List<int> primes = new List<int>();
      for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
         if ((int) values.GetValue(ctr) == 0) 
            primes.Add(ctr);
      return primes.ToArray();
   }   
}
// The example displays the following output:
//    Primes less than 100:
//       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
open System

let getPrimes maxPrime =
    let values = Array.CreateInstance(typeof<int>, [| maxPrime - 1 |], [| 2 |])
    // Use Sieve of Eratosthenes to determine prime numbers.
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 |> float |> sqrt |> ceil |> int do
        if values.GetValue i :?> int <> 1 then
            for multiplier = i to maxPrime / 2 do
                if i * multiplier <= maxPrime then
                    values.SetValue(1, i * multiplier)

    [| for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
        if values.GetValue i :?> int = 0 then
            i |]

let maxPrime = 100
let primes = getPrimes maxPrime
printfn $"Primes less than {maxPrime}:"
printfn $"""   {String.Join(" ", primes)}"""

// The example displays the following output:
//    Primes less than 100:
//       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Module Example
   Public Sub Main()
      Dim maxPrime As Integer = 100
      Dim primes() As Integer = GetPrimes(maxPrime)
      Console.WriteLine("Primes less than {0}:", maxPrime)
      Console.WriteLine("   {0}", String.Join(" ", primes))
   End Sub

   Private Function GetPrimes(maxPrime As Integer) As Integer()
      Dim values As Array = Array.CreateInstance(GetType(Integer), _
                              New Integer() { maxPrime - 1}, New Integer(){ 2 })
        ' Use Sieve of Eratosthenes to determine prime numbers.
      For ctr As Integer = values.GetLowerBound(0) To _
                           CInt(Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))))
         If CInt(values.GetValue(ctr)) = 1 Then Continue For

         For multiplier As Integer = ctr To maxPrime \ 2
            If ctr * multiplier <= maxPrime Then values.SetValue(1, ctr * multiplier)
         Next
      Next

      Dim primes As New System.Collections.Generic.List(Of Integer)
      For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
         If CInt(values.GetValue(ctr)) = 0 Then primes.Add(ctr)
      Next
      Return primes.ToArray()
   End Function
End Module

' The example displays the following output:
'    Primes less than 100:
'       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

注解

如果是separator或如果第一个元素以外的任何元素valuesnull,则改用空字符串 (String.Empty) 。null 如果第一个元素为 valuesnull,请参阅“调用方备注”部分。

Join(String, Object[]) 是一种方便的方法,可用于连接对象数组中的每个元素,而无需将其元素显式转换为字符串。 数组中每个对象的字符串表示形式是通过调用该对象的方法派生的 ToString

调用方说明

仅 .NET Framework:如果第一个元素是valuesnull,则Join(String, Object[])该方法不会连接元素,values而是返回Empty。 此问题提供了许多解决方法。 最简单的方法是向数组的第一个元素赋值 Empty ,如以下示例所示。

object[] values = { null, "Cobb", 4189, 11434, .366 };
if (values[0] == null) values[0] = String.Empty;
Console.WriteLine(String.Join("|", values));

// The example displays the following output:
//      |Cobb|4189|11434|0.366
let values: obj[] = [| null; "Cobb"; 4189; 11434; 0.366 |]
if values[0] = null then 
   values[0] <- String.Empty
printfn $"""{String.Join("|", values)}"""

// The example displays the following output:
//      |Cobb|4189|11434|0.366
Dim values() As Object = { Nothing, "Cobb", 4189, 11434, .366 }
If values(0) Is Nothing Then values(0) = String.Empty
Console.WriteLine(String.Join("|", values))
' The example displays the following output:
'      |Cobb|4189|11434|0.366

另请参阅

适用于

Join(Char, ReadOnlySpan<Object>)

Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接对象范围的字符串表示形式。

public:
 static System::String ^ Join(char separator, ReadOnlySpan<System::Object ^> values);
public static string Join(char separator, scoped ReadOnlySpan<object?> values);
static member Join : char * ReadOnlySpan<obj> -> string
Public Shared Function Join (separator As Char, values As ReadOnlySpan(Of Object)) As String

参数

separator
Char

要用作分隔符的字符。 separator 仅当值具有多个元素时,才会包含在返回的字符串中。

values
ReadOnlySpan<Object>

将串联其字符串表示形式的对象的范围。

返回

由字符分隔separatorvalues元素组成的字符串。 -或 - Empty 如果有 values 零个元素。

适用于

Join(Char, Object[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接对象数组的字符串表示形式。

public:
 static System::String ^ Join(char separator, ... cli::array <System::Object ^> ^ values);
public static string Join(char separator, params object?[] values);
public static string Join(char separator, params object[] values);
static member Join : char * obj[] -> string
Public Shared Function Join (separator As Char, ParamArray values As Object()) As String

参数

separator
Char

要用作分隔符的字符。 separator 仅当包含多个元素时 values ,才会包含在返回的字符串中。

values
Object[]

将串联其字符串表示形式的对象的数组。

返回

由字符分隔separatorvalues元素组成的字符串。

-或-

Empty 如果有 values 零个元素。

例外

valuesnull

生成的字符串的长度溢出允许的最大长度(Int32.MaxValue)。

适用于

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

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接集合的成员。

public:
generic <typename T>
 static System::String ^ Join(char separator, System::Collections::Generic::IEnumerable<T> ^ values);
public static string Join<T>(char separator, System.Collections.Generic.IEnumerable<T> values);
static member Join : char * seq<'T> -> string
Public Shared Function Join(Of T) (separator As Char, values As IEnumerable(Of T)) As String

类型参数

T

成员 values的类型。

参数

separator
Char

要用作分隔符的字符。 separator 仅当包含多个元素时 values ,才会包含在返回的字符串中。

values
IEnumerable<T>

包含要连接的对象的集合。

返回

由字符分隔separator的成员values组成的字符串。

-或-

Empty 如果没有 values 元素。

例外

valuesnull

生成的字符串的长度溢出允许的最大长度(Int32.MaxValue)。

适用于

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

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

使用每个成员之间的指定分隔符连接集合的成员。

public:
generic <typename T>
 static System::String ^ Join(System::String ^ separator, System::Collections::Generic::IEnumerable<T> ^ values);
public static string Join<T>(string separator, System.Collections.Generic.IEnumerable<T> values);
public static string Join<T>(string? separator, System.Collections.Generic.IEnumerable<T> values);
[System.Runtime.InteropServices.ComVisible(false)]
public static string Join<T>(string separator, System.Collections.Generic.IEnumerable<T> values);
static member Join : string * seq<'T> -> string
[<System.Runtime.InteropServices.ComVisible(false)>]
static member Join : string * seq<'T> -> string
Public Shared Function Join(Of T) (separator As String, values As IEnumerable(Of T)) As String

类型参数

T

成员 values的类型。

参数

separator
String

要用作分隔符的字符串。 separator 仅当包含多个元素时 values ,才会包含在返回的字符串中。

values
IEnumerable<T>

包含要连接的对象的集合。

返回

由字符串分隔separatorvalues元素组成的字符串。

-或-

Empty 如果没有 values 元素。

属性

例外

valuesnull

生成的字符串的长度溢出允许的最大长度(Int32.MaxValue)。

示例

以下示例使用 Eratosthenes 算法的 Sieve 计算小于或等于 100 的质数。 它将结果分配给整数 List<T> 类型的对象,然后 Join<T>(String, IEnumerable<T>) 传递给该方法。

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      int maxPrime = 100;
      List<int> primes = GetPrimes(maxPrime);
      Console.WriteLine("Primes less than {0}:", maxPrime);
      Console.WriteLine("   {0}", String.Join(" ", primes));
   }

   private static List<int> GetPrimes(int maxPrime)
   {
      Array values = Array.CreateInstance(typeof(int), 
                              new int[] { maxPrime - 1}, new int[] { 2 });
      // Use Sieve of Eratosthenes to determine prime numbers.
      for (int ctr = values.GetLowerBound(0); ctr <= (int) Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))); ctr++)
      {
                           
         if ((int) values.GetValue(ctr) == 1) continue;
         
         for (int multiplier = ctr; multiplier <=  maxPrime / 2; multiplier++)
            if (ctr * multiplier <= maxPrime)
               values.SetValue(1, ctr * multiplier);
      }      
      
      List<int> primes = new List<int>();
      for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
         if ((int) values.GetValue(ctr) == 0) 
            primes.Add(ctr);
      return primes;
   }   
}
// The example displays the following output:
//    Primes less than 100:
//       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
open System

let getPrimes maxPrime =
    let values = Array.CreateInstance(typeof<int>, [| maxPrime - 1 |], [| 2 |])
    // Use Sieve of Eratosthenes to determine prime numbers.
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 |> float |> sqrt |> ceil |> int do
        if values.GetValue i <> 1 then
            for multiplier = i to maxPrime / 2 do
                if i * multiplier <= maxPrime then
                    values.SetValue(1, i * multiplier)

    let primes = ResizeArray()
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
        if values.GetValue i :?> int = 0 then
            primes.Add i
    primes

let maxPrime = 100
let primes = getPrimes maxPrime
printfn $"Primes less than {maxPrime}:"
printfn $"""   {String.Join(" ", primes)}"""
// The example displays the following output:
//    Primes less than 100:
//       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Imports System.Collections.Generic

Module Example
   Public Sub Main()
      Dim maxPrime As Integer = 100
      Dim primes As List(Of Integer) = GetPrimes(maxPrime)
      Console.WriteLine("Primes less than {0}:", maxPrime)
      Console.WriteLine("   {0}", String.Join(" ", primes))
   End Sub

   Private Function GetPrimes(maxPrime As Integer) As List(Of Integer)
      Dim values As Array = Array.CreateInstance(GetType(Integer), _
                              New Integer() { maxPrime - 1}, New Integer(){ 2 })
        ' Use Sieve of Eratosthenes to determine prime numbers.
      For ctr As Integer = values.GetLowerBound(0) To _
                           CInt(Math.Ceiling(Math.Sqrt(values.GetUpperBound(0))))
         If CInt(values.GetValue(ctr)) = 1 Then Continue For

         For multiplier As Integer = ctr To maxPrime \ 2
            If ctr * multiplier <= maxPrime Then values.SetValue(1, ctr * multiplier)
         Next
      Next

      Dim primes As New System.Collections.Generic.List(Of Integer)
      For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
         If CInt(values.GetValue(ctr)) = 0 Then primes.Add(ctr)
      Next
      Return primes
   End Function
End Module

' The example displays the following output:
'    Primes less than 100:
'       2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

注解

null如果是separator,则改用空字符串(String.Empty)。 如果任一成员valuesnull,则改用空字符串。

Join<T>(String, IEnumerable<T>) 是一种方便的方法,可让你连接集合的每个成员 IEnumerable<T> ,而无需先将它们转换为字符串。 集合中 IEnumerable<T> 每个对象的字符串表示形式通过调用该对象的 ToString 方法派生。

此方法特别适用于 Language-Integrated Query (LINQ) 查询表达式。 例如,下面的代码定义了一个非常简单的 Animal 类,该类包含动物的名称及其所属的顺序。 然后,它定义一个 List<T> 包含多个 Animal 对象的对象。 调用 Enumerable.Where 扩展方法以提取 AnimalOrder 属性等于“Rodent”的对象。 结果将 Join<T>(String, IEnumerable<T>) 传递给方法。

using System;
using System.Collections.Generic;
using System.Linq;

public class Animal
{
   public string Kind;
   public string Order;
   
   public Animal(string kind, string order)
   {
      this.Kind = kind;
      this.Order = order;
   }
   
   public override string ToString()
   {
      return this.Kind;
   }
}

public class Example
{
   public static void Main()
   {
      List<Animal> animals = new List<Animal>();
      animals.Add(new Animal("Squirrel", "Rodent"));
      animals.Add(new Animal("Gray Wolf", "Carnivora"));
      animals.Add(new Animal("Capybara", "Rodent"));
      string output = String.Join(" ", animals.Where( animal => 
                      (animal.Order == "Rodent")));
      Console.WriteLine(output);  
   }
}
// The example displays the following output:
//      Squirrel Capybara
// This example uses F#'s Seq.filter function instead of Linq.
open System

type Animal =
  { Kind: string
    Order: string }
    override this.ToString() =
        this.Kind

let animals = ResizeArray()
animals.Add { Kind = "Squirrel"; Order = "Rodent" }
animals.Add { Kind = "Gray Wolf"; Order = "Carnivora" }
animals.Add { Kind = "Capybara"; Order = "Rodent" }
String.Join(" ", animals |> Seq.filter (fun animal -> animal.Order = "Rodent"))
|> printfn "%s"
// The example displays the following output:
//      Squirrel Capybara
Imports System.Collections.Generic

Public Class Animal
   Public Kind As String
   Public Order As String

   Public Sub New(kind As String, order As String)
      Me.Kind = kind
      Me.Order = order
   End Sub

   Public Overrides Function ToString() As String
      Return Me.Kind
   End Function
End Class

Module Example
   Public Sub Main()
      Dim animals As New List(Of Animal)
      animals.Add(New Animal("Squirrel", "Rodent"))
      animals.Add(New Animal("Gray Wolf", "Carnivora"))
      animals.Add(New Animal("Capybara", "Rodent"))
      Dim output As String = String.Join(" ", animals.Where(Function(animal) _
                                           animal.Order = "Rodent"))
      Console.WriteLine(output)
   End Sub
End Module

' The example displays the following output:
'      Squirrel Capybara

另请参阅

适用于