ใน. NET 4.0 การรวมสตริงมีโอเวอร์โหลดparams object[]
ดังนั้นจึงทำได้ง่ายเพียงแค่:
int[] ids = new int[] { 1, 2, 3 };
string.Join(",", ids);
ตัวอย่าง
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));
ใน. NET 2.0 นั้นยากกว่าเล็กน้อยเนื่องจากไม่มีการโอเวอร์โหลด ดังนั้นคุณต้องมีวิธีการทั่วไปของคุณเอง:
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;
}
ใน. NET 3.5 คุณสามารถใช้วิธีการขยาย:
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;
}
}
ดังนั้นคุณสามารถใช้วิธีการขยาย JoinArray
int[] ids = new int[] { 1, 2, 3 };
string strIdList = ids.JoinArray(",");
คุณยังสามารถใช้วิธีการขยายนั้นใน. NET 2.0 ได้หากคุณเพิ่ม ExtensionAttribute ลงในโค้ดของคุณ:
// 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 {}
}