Llegeix en anglès

Comparteix a través de


String.Concat Método

Definición

Concatena una o varias instancias de Stringo las representaciones String de los valores de una o varias instancias de Object.

Sobrecargas

Concat(String, String, String, String)

Concatena cuatro instancias especificadas de String.

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

Concatena las representaciones de cadena de cuatro intervalos de caracteres de solo lectura especificados.

Concat(Object, Object, Object, Object)

Concatena las representaciones de cadena de cuatro objetos especificados y los objetos especificados en una lista de parámetros de longitud variable opcional.

Concat(String, String, String)

Concatena tres instancias especificadas de String.

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

Concatena las representaciones de cadena de tres intervalos de caracteres de solo lectura especificados.

Concat(Object, Object, Object)

Concatena las representaciones de cadena de tres objetos especificados.

Concat(String, String)

Concatena dos instancias especificadas de String.

Concat(Object)

Crea la representación de cadena de un objeto especificado.

Concat(Object, Object)

Concatena las representaciones de cadena de dos objetos especificados.

Concat(String[])

Concatena los elementos de una matriz de String especificada.

Concat(ReadOnlySpan<String>)

Concatena los elementos de un intervalo especificado de String.

Concat(ReadOnlySpan<Object>)

Concatena las representaciones de cadena de los elementos en un intervalo de objetos especificado.

Concat(Object[])

Concatena las representaciones de cadena de los elementos de una matriz de Object especificada.

Concat(IEnumerable<String>)

Concatena los miembros de una colección construida IEnumerable<T> de tipo String.

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

Concatena las representaciones de cadena de dos intervalos de caracteres de solo lectura especificados.

Concat<T>(IEnumerable<T>)

Concatena los miembros de una implementación de IEnumerable<T>.

Comentarios

Nota

También puede usar el operador de concatenación de cadenas del lenguaje, como + en C# y F#, o & y + en Visual Basic, para concatenar cadenas. Ambos compiladores convierten el operador de concatenación en una llamada a una de las sobrecargas de String.Concat.

Concat(String, String, String, String)

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

Concatena cuatro instancias especificadas de String.

public static string Concat (string str0, string str1, string str2, string str3);
public static string Concat (string? str0, string? str1, string? str2, string? str3);

Parámetros

str0
String

Primera cadena que se va a concatenar.

str1
String

Segunda cadena que se va a concatenar.

str2
String

Tercera cadena que se va a concatenar.

str3
String

Cuarta cadena que se va a concatenar.

Devoluciones

Concatenación de str0, str1, str2y str3.

Ejemplos

En el ejemplo siguiente se define una matriz de palabras de cuatro letras y se almacenan sus letras individuales en una matriz de cadenas para codificarlas. A continuación, llama al método Concat(String, String, String, String) para volver a ensamblar las palabras codificadas.

using System;
using System.Collections;

public class Example
{
   public static void Main()
   {
      const int WORD_SIZE = 4;
      
      // Define some 4-letter words to be scrambled.
      string[] words = { "home", "food", "game", "rest" };
      // Define two arrays equal to the number of letters in each word.
      double[] keys = new double[WORD_SIZE];
      string[] letters = new string[WORD_SIZE];
      // Initialize the random number generator.
      Random rnd = new Random();
      
      // Scramble each word.
      foreach (string word in words)
      {
         for (int ctr = 0; ctr < word.Length; ctr++)
         {
            // Populate the array of keys with random numbers.
            keys[ctr] = rnd.NextDouble();
            // Assign a letter to the array of letters.
            letters[ctr] = word[ctr].ToString();
         }   
         // Sort the array. 
         Array.Sort(keys, letters, 0, WORD_SIZE, Comparer.Default);      
         // Display the scrambled word.
         string scrambledWord = String.Concat(letters[0], letters[1], 
                                              letters[2], letters[3]);
         Console.WriteLine("{0} --> {1}", word, scrambledWord);
      } 
   }
}
// The example displays output like the following:
//       home --> mheo
//       food --> oodf
//       game --> aemg
//       rest --> trse

Comentarios

El método concatena str0, str1, str2y str3; no agrega ningún delimitador.

Consulte también

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

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

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

Concatena las representaciones de cadena de cuatro intervalos de caracteres de solo lectura especificados.

public static string Concat (ReadOnlySpan<char> str0, ReadOnlySpan<char> str1, ReadOnlySpan<char> str2, ReadOnlySpan<char> str3);

Parámetros

str0
ReadOnlySpan<Char>

El primer intervalo de caracteres de solo lectura que se va a concatenar.

str1
ReadOnlySpan<Char>

Segundo intervalo de caracteres de solo lectura que se va a concatenar.

str2
ReadOnlySpan<Char>

Tercer intervalo de caracteres de solo lectura que se va a concatenar.

str3
ReadOnlySpan<Char>

Cuarto intervalo de caracteres de solo lectura que se va a concatenar.

Devoluciones

Representaciones de cadena concatenadas de los valores de str0, str1, str2 y str3.

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9

Concat(Object, Object, Object, Object)

Importante

Esta API no es conforme a CLS.

Concatena las representaciones de cadena de cuatro objetos especificados y los objetos especificados en una lista de parámetros de longitud variable opcional.

[System.CLSCompliant(false)]
public static string Concat (object arg0, object arg1, object arg2, object arg3);

Parámetros

arg0
Object

Primer objeto que se va a concatenar.

arg1
Object

Segundo objeto que se va a concatenar.

arg2
Object

Tercer objeto que se va a concatenar.

arg3
Object

Cuarto objeto que se va a concatenar.

Devoluciones

Representación de cadena concatenada de cada valor de la lista de parámetros.

Atributos

Ejemplos

En el ejemplo siguiente se muestra el uso del método Concat(Object, Object, Object, Object) para concatenar una lista de parámetros de variable. En este caso, se llama al método con nueve parámetros.

using System;
using System.Collections;

public class Example
{
   public static void Main()
   {
      const int WORD_SIZE = 4;
      
      // Define some 4-letter words to be scrambled.
      string[] words = { "home", "food", "game", "rest" };
      // Define two arrays equal to the number of letters in each word.
      double[] keys = new double[WORD_SIZE];
      string[] letters = new string[WORD_SIZE];
      // Initialize the random number generator.
      Random rnd = new Random();
      
      // Scramble each word.
      foreach (string word in words)
      {
         for (int ctr = 0; ctr < word.Length; ctr++)
         {
            // Populate the array of keys with random numbers.
            keys[ctr] = rnd.NextDouble();
            // Assign a letter to the array of letters.
            letters[ctr] = word[ctr].ToString();
         }   
         // Sort the array. 
         Array.Sort(keys, letters, 0, WORD_SIZE, Comparer.Default);      
         // Display the scrambled word.
         string scrambledWord = String.Concat(letters[0], letters[1], 
                                              letters[2], letters[3]);
         Console.WriteLine("{0} --> {1}", word, scrambledWord);
      } 
   }
}
// The example displays output like the following:
//       home --> mheo
//       food --> oodf
//       game --> aemg
//       rest --> trse

Comentarios

Nota

Esta API no es compatible con CLS. La alternativa conforme a CLS es String.Concat(Object[]). Los compiladores de C# y Visual Basic resuelven automáticamente una llamada a este método como una llamada a String.Concat(Object[]).

El método concatena cada objeto de la lista de parámetros llamando a su método ToString sin parámetros; no agrega ningún delimitador.

String.Empty se usa en lugar de cualquier argumento NULL.

Nota

El último parámetro del método Concat es una lista opcional delimitada por comas de uno o varios objetos adicionales para concatenar.

Notas a los autores de las llamadas

Este método está marcado con la palabra clave vararg, lo que significa que admite un número variable de parámetros. Se puede llamar al método desde Visual C++, pero no se puede llamar desde código de C# o Visual Basic. Los compiladores de C# y Visual Basic resuelven llamadas a Concat(Object, Object, Object, Object) como llamadas a Concat(Object[]).

Se aplica a

.NET Framework 4.8.1 i altres versions
Producte Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

Concat(String, String, String)

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

Concatena tres instancias especificadas de String.

public static string Concat (string str0, string str1, string str2);
public static string Concat (string? str0, string? str1, string? str2);

Parámetros

str0
String

Primera cadena que se va a concatenar.

str1
String

Segunda cadena que se va a concatenar.

str2
String

Tercera cadena que se va a concatenar.

Devoluciones

Concatenación de str0, str1y str2.

Ejemplos

En el ejemplo siguiente se usa el método Concat para concatenar tres cadenas y mostrar el resultado.

using System;

public class Example
{
   public static void Main()
   {
      String s1 = "We went to a bookstore, ";
      String s2 = "a movie, ";
      String s3 = "and a restaurant.";

      var s = String.Concat(s1, s2, s3);
      Console.WriteLine(s);
   }
}
// The example displays the following output:
//      We went to a bookstore, a movie, and a restaurant.

Comentarios

El método concatena str0, str1y str2; no agrega ningún delimitador.

Consulte también

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

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

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

Concatena las representaciones de cadena de tres intervalos de caracteres de solo lectura especificados.

public static string Concat (ReadOnlySpan<char> str0, ReadOnlySpan<char> str1, ReadOnlySpan<char> str2);

Parámetros

str0
ReadOnlySpan<Char>

El primer intervalo de caracteres de solo lectura que se va a concatenar.

str1
ReadOnlySpan<Char>

Segundo intervalo de caracteres de solo lectura que se va a concatenar.

str2
ReadOnlySpan<Char>

Tercer intervalo de caracteres de solo lectura que se va a concatenar.

Devoluciones

Representaciones de cadena concatenadas de los valores de str0, str1 y str2.

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9

Concat(Object, Object, Object)

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

Concatena las representaciones de cadena de tres objetos especificados.

public static string Concat (object arg0, object arg1, object arg2);
public static string Concat (object? arg0, object? arg1, object? arg2);

Parámetros

arg0
Object

Primer objeto que se va a concatenar.

arg1
Object

Segundo objeto que se va a concatenar.

arg2
Object

Tercer objeto que se va a concatenar.

Devoluciones

Representaciones de cadena concatenadas de los valores de arg0, arg1y arg2.

Ejemplos

En el ejemplo siguiente se muestra el método Concat.

using System;

class stringConcat5 {
    public static void Main() {
    int i = -123;
    Object o = i;
    Object[] objs = new Object[] {-123, -456, -789};

    Console.WriteLine("Concatenate 1, 2, and 3 objects:");
    Console.WriteLine("1) {0}", String.Concat(o));
    Console.WriteLine("2) {0}", String.Concat(o, o));
    Console.WriteLine("3) {0}", String.Concat(o, o, o));

    Console.WriteLine("\nConcatenate 4 objects and a variable length parameter list:");
    Console.WriteLine("4) {0}", String.Concat(o, o, o, o));
    Console.WriteLine("5) {0}", String.Concat(o, o, o, o, o));

    Console.WriteLine("\nConcatenate a 3-element object array:");
    Console.WriteLine("6) {0}", String.Concat(objs));
    }
}
// The example displays the following output:
//    Concatenate 1, 2, and 3 objects:
//    1) -123
//    2) -123-123
//    3) -123-123-123
//
//    Concatenate 4 objects and a variable length parameter list:
//    4) -123-123-123-123
//    5) -123-123-123-123-123
//
//    Concatenate a 3-element object array:
//    6) -123-456-789

Comentarios

El método concatena arg0, arg1y arg2 llamando al método ToString sin parámetros de cada objeto; no agrega ningún delimitador.

String.Empty se usa en lugar de cualquier argumento NULL.

Consulte también

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Concat(String, String)

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

Concatena dos instancias especificadas de String.

public static string Concat (string str0, string str1);
public static string Concat (string? str0, string? str1);

Parámetros

str0
String

Primera cadena que se va a concatenar.

str1
String

Segunda cadena que se va a concatenar.

Devoluciones

Concatenación de str0 y str1.

Ejemplos

En el ejemplo siguiente se concatena el nombre, el medio y el apellido de una persona.

using System;

public class ConcatTest {
    public static void Main() {

        // we want to simply quickly add this person's name together
        string fName = "Simon";
        string mName = "Jake";
        string lName = "Harrows";

        // because we want a name to appear with a space in between each name,
        // put a space on the front of the middle, and last name, allowing for
        // the fact that a space may already be there
        mName = " " + mName.Trim();
        lName = " " + lName.Trim();

        // this line simply concatenates the two strings
        Console.WriteLine("Welcome to this page, '{0}'!", string.Concat( string.Concat(fName, mName), lName ) );
    }
}
// The example displays the following output:
//        Welcome to this page, 'Simon Jake Harrows'!

Comentarios

El método concatena str0 y str1; no agrega ningún delimitador.

Se usa una cadena Empty en lugar de cualquier argumento NULL.

Consulte también

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Concat(Object)

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

Crea la representación de cadena de un objeto especificado.

public static string Concat (object arg0);
public static string Concat (object? arg0);

Parámetros

arg0
Object

Objeto que se va a representar o null.

Devoluciones

Representación de cadena del valor de arg0, o Empty si arg0 es null.

Ejemplos

En el ejemplo siguiente se muestra el método Concat.

using System;

class stringConcat5 {
    public static void Main() {
    int i = -123;
    Object o = i;
    Object[] objs = new Object[] {-123, -456, -789};

    Console.WriteLine("Concatenate 1, 2, and 3 objects:");
    Console.WriteLine("1) {0}", String.Concat(o));
    Console.WriteLine("2) {0}", String.Concat(o, o));
    Console.WriteLine("3) {0}", String.Concat(o, o, o));

    Console.WriteLine("\nConcatenate 4 objects and a variable length parameter list:");
    Console.WriteLine("4) {0}", String.Concat(o, o, o, o));
    Console.WriteLine("5) {0}", String.Concat(o, o, o, o, o));

    Console.WriteLine("\nConcatenate a 3-element object array:");
    Console.WriteLine("6) {0}", String.Concat(objs));
    }
}
// The example displays the following output:
//    Concatenate 1, 2, and 3 objects:
//    1) -123
//    2) -123-123
//    3) -123-123-123
//
//    Concatenate 4 objects and a variable length parameter list:
//    4) -123-123-123-123
//    5) -123-123-123-123-123
//
//    Concatenate a 3-element object array:
//    6) -123-456-789

Comentarios

El método Concat(Object) representa arg0 como una cadena llamando a su método ToString sin parámetros.

Consulte también

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Concat(Object, Object)

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

Concatena las representaciones de cadena de dos objetos especificados.

public static string Concat (object arg0, object arg1);
public static string Concat (object? arg0, object? arg1);

Parámetros

arg0
Object

Primer objeto que se va a concatenar.

arg1
Object

Segundo objeto que se va a concatenar.

Devoluciones

Representaciones de cadena concatenadas de los valores de arg0 y arg1.

Ejemplos

En el ejemplo siguiente se muestra el método Concat.

using System;

class stringConcat5 {
    public static void Main() {
    int i = -123;
    Object o = i;
    Object[] objs = new Object[] {-123, -456, -789};

    Console.WriteLine("Concatenate 1, 2, and 3 objects:");
    Console.WriteLine("1) {0}", String.Concat(o));
    Console.WriteLine("2) {0}", String.Concat(o, o));
    Console.WriteLine("3) {0}", String.Concat(o, o, o));

    Console.WriteLine("\nConcatenate 4 objects and a variable length parameter list:");
    Console.WriteLine("4) {0}", String.Concat(o, o, o, o));
    Console.WriteLine("5) {0}", String.Concat(o, o, o, o, o));

    Console.WriteLine("\nConcatenate a 3-element object array:");
    Console.WriteLine("6) {0}", String.Concat(objs));
    }
}
// The example displays the following output:
//    Concatenate 1, 2, and 3 objects:
//    1) -123
//    2) -123-123
//    3) -123-123-123
//
//    Concatenate 4 objects and a variable length parameter list:
//    4) -123-123-123-123
//    5) -123-123-123-123-123
//
//    Concatenate a 3-element object array:
//    6) -123-456-789

Comentarios

El método concatena arg0 y arg1 llamando al método ToString sin parámetros de arg0 y arg1; no agrega ningún delimitador.

String.Empty se usa en lugar de cualquier argumento NULL.

Si alguno de los argumentos es una referencia de matriz, el método concatena una cadena que representa esa matriz, en lugar de sus miembros (por ejemplo, "System.String[]").

Consulte también

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Concat(String[])

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

Importante

Esta API no es conforme a CLS.

Concatena los elementos de una matriz de String especificada.

public static string Concat (params string[] values);
public static string Concat (params string?[] values);
[System.CLSCompliant(false)]
public static string Concat (params string[] values);

Parámetros

values
String[]

Matriz de instancias de cadena.

Devoluciones

Elementos concatenados de values.

Atributos

Excepciones

values es null.

Memoria insuficiente.

Ejemplos

En el ejemplo siguiente se muestra el uso del método Concat con una matriz String.

using System;

public class Example
{
    public static void Main()
    {
        // Make an array of strings. Note that we have included spaces.
        string [] s = { "hello ", "and ", "welcome ", "to ",
                        "this ", "demo! " };

        // Put all the strings together.
        Console.WriteLine(string.Concat(s));

        // Sort the strings, and put them together.
        Array.Sort(s);
        Console.WriteLine(string.Concat(s));
    }
}
// The example displays the following output:
//       hello and welcome to this demo!
//       and demo! hello this to welcome

Comentarios

El método concatena cada objeto en values; no agrega ningún delimitador.

Se usa una cadena Empty en lugar de cualquier objeto NULL de la matriz.

Consulte también

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Concat(ReadOnlySpan<String>)

Concatena los elementos de un intervalo especificado de String.

public static string Concat (scoped ReadOnlySpan<string?> values);

Parámetros

values
ReadOnlySpan<String>

Intervalo de instancias de String.

Devoluciones

Elementos concatenados de values.

Se aplica a

.NET 9
Producte Versions
.NET 9

Concat(ReadOnlySpan<Object>)

Concatena las representaciones de cadena de los elementos en un intervalo de objetos especificado.

public static string Concat (scoped ReadOnlySpan<object?> args);

Parámetros

args
ReadOnlySpan<Object>

Intervalo de objetos que contiene los elementos que se van a concatenar.

Devoluciones

Representaciones de cadena concatenadas de los valores de los elementos de args.

Se aplica a

.NET 9
Producte Versions
.NET 9

Concat(Object[])

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

Concatena las representaciones de cadena de los elementos de una matriz de Object especificada.

public static string Concat (params object[] args);
public static string Concat (params object?[] args);

Parámetros

args
Object[]

Matriz de objetos que contiene los elementos que se van a concatenar.

Devoluciones

Representaciones de cadena concatenadas de los valores de los elementos de args.

Excepciones

args es null.

Memoria insuficiente.

Ejemplos

En el ejemplo siguiente se muestra el uso del método Concat con una matriz de Object.

using System;

public class ConcatTest {
    public static void Main() {
        // Create a group of objects.
        Test1 t1 = new Test1();
        Test2 t2 = new Test2();
        int i = 16;
        string s = "Demonstration";

        // Place the objects in an array.
        object [] o = { t1, i, t2, s };

        // Concatenate the objects together as a string. To do this,
        // the ToString method of each of the objects is called.
        Console.WriteLine(string.Concat(o));
    }
}

// Create two empty test classes.
class Test1 {
}

class Test2 {
}
// The example displays the following output:
//       Test116Test2Demonstration

Comentarios

El método concatena cada objeto en args llamando al método sin parámetros ToString de ese objeto; no agrega ningún delimitador.

String.Empty se usa en lugar de cualquier objeto NULL de la matriz.

Notas a los autores de las llamadas

El código de C++ no llama a este método. El compilador de C++ resuelve las llamadas a Concat que tienen cuatro o más parámetros de objeto como una llamada a Concat(Object, Object, Object, Object).

Consulte también

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Concat(IEnumerable<String>)

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

Concatena los miembros de una colección construida IEnumerable<T> de tipo String.

public static string Concat (System.Collections.Generic.IEnumerable<string> values);
public static string Concat (System.Collections.Generic.IEnumerable<string?> values);
[System.Runtime.InteropServices.ComVisible(false)]
public static string Concat (System.Collections.Generic.IEnumerable<string> values);

Parámetros

values
IEnumerable<String>

Objeto de colección que implementa IEnumerable<T> y cuyo argumento de tipo genérico es String.

Devoluciones

Las cadenas concatenadas de valueso Empty si values es una IEnumerable(Of String)vacía.

Atributos

Excepciones

values es null.

Ejemplos

En el ejemplo siguiente se usa el algoritmo Sieve de Eratosthenes para calcular los números primos que son menores o iguales a 100. Asigna el resultado a un objeto List<T> de tipo String, que luego pasa al método Concat(IEnumerable<String>).

using System;
using System.Collections.Generic;

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

   private static IEnumerable<String> GetPrimes(int maxPrime)
   {
      Array values = Array.CreateInstance(typeof(int), 
                              new int[] { maxPrime - 1}, new int[] { 2 }); 
      // Use Sieve of Erathsthenes 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<String> primes = new List<String>();
      for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
         if ((int) values.GetValue(ctr) == 0) 
            primes.Add(ctr.ToString() + " ");
      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

Comentarios

El método concatena cada objeto en values; no agrega ningún delimitador. Para especificar un delimitador entre cada miembro de values, llame al método Join(String, IEnumerable<String>).

Se usa una cadena Empty en lugar de cualquier elemento NULL en values.

Si values es un IEnumerable(Of String)vacío, el método devuelve String.Empty. Si values es null, el método produce una excepción de ArgumentNullException.

Concat(IEnumerable<String>) es un método cómodo que permite concatenar cada elemento de una colección de IEnumerable(Of String) sin convertir primero los elementos en una matriz de cadenas. Resulta especialmente útil con expresiones de consulta de Language-Integrated Query (LINQ). En el ejemplo siguiente se pasa un objeto List(Of String) que contiene las letras mayúsculas o minúsculas del alfabeto a una expresión lambda que selecciona letras iguales o mayores que una letra determinada (que, en el ejemplo, es "M"). La colección IEnumerable(Of String) que devuelve el método Enumerable.Where se pasa al método Concat(IEnumerable<String>) para mostrar el resultado como una sola cadena.

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

public class Example
{
   public static void Main()
   {
      string output = String.Concat( 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:
//      MNOPQRSTUVWXYZ

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

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

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

Concatena las representaciones de cadena de dos intervalos de caracteres de solo lectura especificados.

public static string Concat (ReadOnlySpan<char> str0, ReadOnlySpan<char> str1);

Parámetros

str0
ReadOnlySpan<Char>

El primer intervalo de caracteres de solo lectura que se va a concatenar.

str1
ReadOnlySpan<Char>

Segundo intervalo de caracteres de solo lectura que se va a concatenar.

Devoluciones

Representaciones de cadena concatenadas de los valores de str0 y str1.

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9

Concat<T>(IEnumerable<T>)

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

Concatena los miembros de una implementación de IEnumerable<T>.

public static string Concat<T> (System.Collections.Generic.IEnumerable<T> values);
[System.Runtime.InteropServices.ComVisible(false)]
public static string Concat<T> (System.Collections.Generic.IEnumerable<T> values);

Parámetros de tipo

T

Tipo de los miembros de values.

Parámetros

values
IEnumerable<T>

Objeto de colección que implementa la interfaz IEnumerable<T>.

Devoluciones

Miembros concatenados de values.

Atributos

Excepciones

values es null.

Ejemplos

En el ejemplo siguiente se define una clase Animal muy sencilla que contiene el nombre de un animal y el orden al que pertenece. A continuación, define un objeto List<T> para que contenga una serie de objetos Animal. Se llama al método de extensión Enumerable.Where para extraer los objetos Animal cuya propiedad Order es igual a "Ratones". El resultado se pasa al método Concat<T>(IEnumerable<T>) y se muestra en la consola.

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.Concat(animals.Where( animal => 
                      (animal.Order == "Rodent")));
      Console.WriteLine(output);  
   }
}
// The example displays the following output:
//      SquirrelCapybara

Comentarios

El método concatena cada objeto en values; no agrega ningún delimitador.

Se usa una cadena Empty en lugar de cualquier argumento NULL.

Concat<T>(IEnumerable<T>) es un método de conveniencia que permite concatenar cada elemento de una colección IEnumerable<T> sin convertir primero los elementos en cadenas. Resulta especialmente útil con expresiones de consulta de Language-Integrated Query (LINQ), como se muestra en el ejemplo. La representación de cadena de cada objeto de la colección IEnumerable<T> se deriva llamando al método ToString del objeto.

Se aplica a

.NET 9 i altres versions
Producte Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0