c# foreach loop written poorly

This foreach loop works fine while testing and only returning 5 rows of data, but I am well aware of how porly it is written , is there a better way, possibly using stringbuilder to re-write this more efficiently?

               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;

Answers


Well yes, it would be more efficient to use 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();

However, it's still not nice code - because you've got all that horrible literal JSON. I would suggest using Json.NET or another JSON library. You can probably use LINQ at that point, e.g.

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);

Aside from anything else, now you don't need to worry about the format of the start value, or whether the title contains quotes etc.

(EDIT: As noted, you should absolutely have using statements for SQL connections etc. That's outside the main point of the question, which is why I didn't mention it here.)


Here is how you would use the 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();

To do this a better way completely, I would use something like JavaScriptSerializer (just a sample):

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);

string.format uses StringBuilder internally.

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;
                }
            }          
        }

Need Your Help

how to organize javascripts using rails and jquery

javascript jquery ruby-on-rails code-organization

i'm working in a big and rich rails web application using tons of javascript. I would like to know if anybody has a tip to organize the javascripts. Today i'm generating a new file named controller...