这个foreach循环在测试时工作正常并且只返回5行数据,但是我很清楚它是如何编写的,是否有更好的方法,可能使用stringbuilder来更有效地重写它?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString);
SqlCommand comm = new SqlCommand("SELECT Title, StartDate FROM tblEvents JOIN eo_UserEventWatch ON eo_UserEventWatch.EventID=tblEvents.ID WHERE eo_UserEventWatch.UserID = @GUID ;", conn);
comm.Parameters.AddWithValue("GUID", userID);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
string result ="{ \"event\" :[";
foreach (DataRow dr in dt.Rows)
{
result += "{\"title\" : \"" + dr[0].ToString() + "\" , \"start\" : \"" + dr[1].ToString() +"\"} ,";
}
result = result.TrimEnd(',');
result += "] }";
return result;
答案 0 :(得分:5)
是的,使用StringBuilder
:
StringBuilder builder = new StringBuilder("{ \"event\" :[");
foreach (DataRow row in dt.Rows)
{
// Alternatively, use AppendFormat
builder.Append("{\"title\" :\"");
.Append(row[0])
.Append("\", \"start\" : \"")
.Append(row[1])
.Append("\"} ,");
}
if (builder[builder.Length - 1] == ',')
{
builder.Length -= 1;
}
builder.Append("] }");
string result = builder.ToString();
然而,它仍然不是漂亮的代码 - 因为你已经拥有了所有可怕的文字JSON。我建议使用Json.NET或其他JSON库。你可以在那时使用LINQ,例如
var result = new { event = dt.AsEnumerable()
.Select(r => new {
title = r.Field<string>(0),
start = r.Field<DateTime>(1))
.ToArray() };
// Or whatever, depending on the library you use
var json = JsonSerializer.ToJson(result);
除此之外,现在您不必担心起始值的格式,或者标题是否包含引号等。
(编辑:如上所述,你应该绝对有using
语句用于SQL连接等。这不在问题的主要部分,这就是为什么我在这里没有提到它。)
答案 1 :(得分:1)
以下是使用StringBuilder的方法
StringBuilder sb = new StringBuilder();
sb.Append("{ \"event\" :[");
foreach(DataRow dr in dt.Rows)
{
sb.Append("{\"title\" : \"");
sb.Append(dr[0].ToString());
sb.Append("\" , \"start\" : \"");
sb.Append(dr[1].ToString());
sb.Append("\"} ,");
}
sb.Remove(sb.ToString().Length - 1, 1);
sb.Append("] }");
return sb.ToString();
为了更好地完成这项工作,我会使用JavaScriptSerializer之类的东西(只是一个样本):
var stuff= (from DataRow dr in dt.AsEnumerable()
select new {
DataItem1 = (string)dr[0];
DataItem2 = (string)dr[1];
});
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(stuff);
答案 2 :(得分:0)
string.format在内部使用StringBuilder。
Is String.Format as efficient as StringBuilder
public static string GetResult()
{
int userId = 0;
string connectionString = ConfigurationManager.ConnectionStrings["connstring"].ConnectionString;
string statement = "SELECT Title, StartDate FROM tblEvents JOIN eo_UserEventWatch ON eo_UserEventWatch.EventID=tblEvents.ID WHERE eo_UserEventWatch.UserID = @GUID";
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(statement, con))
{
con.Open();
cmd.Parameters.AddWithValue("GUID", userId);
using (var dataAdapter = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
string result = "{ \"event\" :[";
foreach (DataRow dr in dt.Rows)
{
result += string.Format(@"{\title\ : \{0}\ , \start\ : \{1}\} ,", dr[0].ToString(), dr[1].ToString());
}
result = result.TrimEnd(',');
result += "] }";
return result;
}
}
}