En .NET 4.0, cadena de combinación tiene una sobrecarga de params object[]
, por lo que es tan simple como:
int[] ids = new int[] { 1, 2, 3 };
string.Join(",", ids);
ejemplo
int[] ids = new int[] { 1, 2, 3 };
System.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM some_table WHERE id_column IN (@bla)");
cmd.CommandText = cmd.CommandText.Replace("@bla", string.Join(",", ids));
En .NET 2.0, que es un poquito más difícil , ya que no hay tal sobrecarga. Por lo que necesita su propio método genérico:
public static string JoinArray<T>(string separator, T[] inputTypeArray)
{
string strRetValue = null;
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
for (int i = 0; i < inputTypeArray.Length; ++i)
{
string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(str))
{
// SQL-Escape
// if (typeof(T) == typeof(string))
// str = str.Replace("'", "''");
ls.Add(str);
} // End if (!string.IsNullOrEmpty(str))
} // Next i
strRetValue= string.Join(separator, ls.ToArray());
ls.Clear();
ls = null;
return strRetValue;
}
En .NET 3.5, puede utilizar los métodos de extensión:
public static class ArrayEx
{
public static string JoinArray<T>(this T[] inputTypeArray, string separator)
{
string strRetValue = null;
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
for (int i = 0; i < inputTypeArray.Length; ++i)
{
string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(str))
{
// SQL-Escape
// if (typeof(T) == typeof(string))
// str = str.Replace("'", "''");
ls.Add(str);
} // End if (!string.IsNullOrEmpty(str))
} // Next i
strRetValue= string.Join(separator, ls.ToArray());
ls.Clear();
ls = null;
return strRetValue;
}
}
por lo que puede utilizar la extensión método JoinArray.
int[] ids = new int[] { 1, 2, 3 };
string strIdList = ids.JoinArray(",");
También puede usar ese método de extensión en .NET 2.0, si agrega ExtensionAttribute a su código:
// you need this once (only), and it must be in this namespace
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
public sealed class ExtensionAttribute : Attribute {}
}
SO rocks! ¡Recibí estas 3 respuestas excelentes en 10 minutos en un domingo! – Riri
A partir de '.NET 4.0' hay métodos que toman una matriz de objetos y un IEnumerable para que pueda hacer' string.join (",", number) '. Sé que la pregunta especifica .NET 3.5, así que no hice de esto una respuesta, pero aparece en búsquedas que no especifican una versión y saber que es posible en 4.0 podría ayudar a alguien. –