Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8167597
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T20:14:42+00:00 2026-06-06T20:14:42+00:00

This foreach loop works fine while testing and only returning 5 rows of data,

  • 0

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;
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T20:14:43+00:00Added an answer on June 6, 2026 at 8:14 pm

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

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can I sort this foreach loop with jQuery? I will sort on id
I am using a foreach loop within PHP similar to this: foreach ($class->getAttributes() as
This is what my loop looks like: var loopResult = Parallel.ForEach(folder.Items.Cast<object>(), (item, loopState) =>
This code runs fine but the for statement by the meant to read back
I'm trying to plot some cities on Google's Geochart. This function works perfectly fine
I am aware that there other questions like this, but their solutions do not
I have a tool that works perfectly fine in Chrome and FF. But with
Now, I have been looking for the answer to this for a while, but
I have a for each loop like this $sn_count = 1; $prodfilter = ;
I have a loop that can look like this: For Each article In artAll

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.