如何在数组成员之间添加逗号等
本文关键字:添加 之间 组成员 数组 | 更新日期: 2023-09-27 18:19:03
我只是在每个单词后面加一个逗号:
foreach (DataRow row in ds.Tables[0].Rows)
{ {
sqlIn += row["personId"] + ", ";
}
然后去掉最后一个不需要的逗号:
sqlIn = sqlIn.TrimEnd(' ', ',');
我觉得在经典ASP的时代。我所做的有c#版本吗?
使用String.Join
String.Join(", ", ds.Tables[0].Rows.Select(r => r["personId"].ToString()));
进一步到B答案正确的语法是
string s = String.Join(", ", ds.Tables[0].Select().Select(r => r["personID"].ToString()));
这是有效的证明
using System;
using System.Linq;
using System.Data.Linq;
using System.Data;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
string col = "personId";
dt.Columns.Add(col, typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(2);
string s = String.Join(", ", ds.Tables[0].Select().Select(r => r["personID"].ToString()));
Console.WriteLine(s);
Console.ReadLine();
}
}
}
输出将是
1, 2
使用String.Join
方法-参见http://msdn.microsoft.com/en-us/library/system.string.join.aspx了解可能的过载。
您希望它转换为CSV格式。
可以使用以下String.Join
重载:
(Method 1) String。将列值转换为数组或
后连接(方法2)您可以使用String。连接过载Join(Of T)(String, IEnumerable(Of T))
,选择扩展方法将返回String类型值的IEnumerable
String.Join(",", (From row In ds.Tables[0].Rows.AsEnumerable Select row["personId")).ToArray)
方法2:String.Join(", ", ds.Tables[0].Rows.Select(row => row["personId"].ToString()));