Trong .NET 4.0, chuỗi tham gia có tình trạng quá tải cho params object[]
, do đó, nó đơn giản như:
int[] ids = new int[] { 1, 2, 3 };
string.Join(",", ids);
dụ
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));
Trong .NET 2.0, nó khó khăn hơn một chút nhỏ , vì không có quá tải. Vì vậy, bạn cần phương pháp của riêng chung:
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;
}
Trong .NET 3.5, bạn có thể sử dụng phương pháp khuyến nông:
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;
}
}
Vì vậy, bạn có thể sử dụng phần mở rộng JoinArray-method.
int[] ids = new int[] { 1, 2, 3 };
string strIdList = ids.JoinArray(",");
Bạn cũng có thể sử dụng phương pháp mở rộng đó trong .NET 2.0, nếu bạn thêm ExtensionAttribute vào mã của mình:
// 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! Tôi có 3 câu trả lời tuyệt vời này trong vòng 10 phút vào Chủ Nhật! – Riri
Kể từ '.NET 4.0', có các phương thức lấy một mảng các đối tượng và một IEnumerable để bạn có thể thực hiện' string.join (",", number) '. Tôi biết câu hỏi chỉ định NET 3.5. Vì vậy, tôi đã không làm cho câu trả lời này, nhưng nó đi lên trong tìm kiếm mà không chỉ định một phiên bản và biết nó có thể trong 4,0 có thể giúp một ai đó. –