C# 如何在数组成员之间添加逗号等?
我只是在每个单词旁边加上逗号:C# 如何在数组成员之间添加逗号等?,c#,C#,我只是在每个单词旁边加上逗号: foreach (DataRow row in ds.Tables[0].Rows) { { sqlIn += row["personId"] + ", "; } 然后删除最后一个不需要的逗号: sqlIn = sqlIn.TrimEnd(' ', ','); 我感觉就像是在经典的ASP时代。我做的有C版本吗?使用String.Join String.Join(", ", ds.Tables[0].Rows.Sel
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()));
使用
String.Join
String.Join(", ", ds.Tables[0].Rows.Select(r => r["personId"].ToString()));
使用
String.Join
方法-有关可能的重载,请参阅 使用String.Join
方法-有关可能的重载,请参阅 您希望将其转换为CSV格式
您可以使用以下String.Join
重载:
(方法1)将列值转换为数组或
(方法2)您可以使用重载连接(Of T)(字符串,IEnumerable(Of T))
,选择扩展方法将返回字符串类型的IEnumerable值
方法1:
String.Join(",", (From row In ds.Tables[0].Rows.AsEnumerable Select row["personId")).ToArray)
String.Join(", ", ds.Tables[0].Rows.Select(row => row["personId"].ToString()));
方法2:
String.Join(",", (From row In ds.Tables[0].Rows.AsEnumerable Select row["personId")).ToArray)
String.Join(", ", ds.Tables[0].Rows.Select(row => row["personId"].ToString()));
遵循此SO线程进行参考:您希望将其转换为CSV格式 您可以使用以下
String.Join
重载:
(方法1)将列值转换为数组或
(方法2)您可以使用重载连接(Of T)(字符串,IEnumerable(Of T))
,选择扩展方法将返回字符串类型的IEnumerable值
方法1:
String.Join(",", (From row In ds.Tables[0].Rows.AsEnumerable Select row["personId")).ToArray)
String.Join(", ", ds.Tables[0].Rows.Select(row => row["personId"].ToString()));
方法2:
String.Join(",", (From row In ds.Tables[0].Rows.AsEnumerable Select row["personId")).ToArray)
String.Join(", ", ds.Tables[0].Rows.Select(row => row["personId"].ToString()));
遵循此SO线程以供参考:进一步了解Bas 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
关于Bas 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
为什么不使用列表或集合并将每个结果添加到该列表或集合中?为什么不使用列表或集合并将每个结果添加到该列表或集合中?