0

I have a problem with a For loop, it looks like this

for (int i = 0; i < dt.Rows.Count; i++)
        //for (int i = 0; i < System.Math.Min(dt.Rows.Count, 3); i++)
        {
            string date = Convert.ToDateTime(dt.Rows[i]["date"]).ToShortDateString();
            schedule[date] = (schedule[date] != null ? schedule[date].ToString() : "")    + Server.HtmlEncode(dt.Rows[i]["todo"].ToString()) + "<br />" + dt.Rows[i]["time"].ToString() + "<br />";
        }
        return schedule;

It's for a Calendar that I have made with an asp.net calendar control. It loops through all records into my Database and gives back my Schedule (records of that date) but I dont want to show more than 3 lines of text that you can add to the calendar(database record). Have you any idea how i can do this ?

Thank you, kind regards, The Designer

5
  • What's wrong with the commented out code? Commented Jul 29, 2011 at 8:31
  • If i use that one i get just only 3 records back from the database so what it does is just give me 3 months back :P , so it only show 3 dates into my whole calendar and what i want is not more than 3 records in one Calendar day for each day. ty George Commented Jul 29, 2011 at 8:35
  • Sorry for my crappy english Dutch man here :) Commented Jul 29, 2011 at 8:36
  • This kind of problem is usually best solved with a SQL query that filters out the correct records from the database directly. Commented Jul 29, 2011 at 8:47
  • Thats a way aswell ty Anders Abel but i want it to keep it abit simple :) Commented Jul 29, 2011 at 8:54

1 Answer 1

2

You could maintain a count of the number of lines you've added for each date:

Dictionary<string, int> schedulesDateCount = new Dictionary<string, int>();

for (int i = 0; i < dt.Rows.Count; i++)
{
    string date = Convert.ToDateTime(dt.Rows[i]["date"]).ToShortDateString();

    if(!schedulesDateCount.ContainsKey(date))
        schedulesDateCount[date] = 0;

    if(schedulesDateCount[date] < 3)
    {
        schedule[date] = (schedule[date] != null ? schedule[date].ToString() : "")    + Server.HtmlEncode(dt.Rows[i]["todo"].ToString()) + "<br />" + dt.Rows[i]["time"].ToString() + "<br />";
        schedulesDateCount[date] = schedulesDateCount[date] + 1;
    }
}
return schedule;
Sign up to request clarification or add additional context in comments.

1 Comment

@George Duckett I think you should replace the .HasKey method with the .ContainsKey Method if(!schedulesDateCount.HasKey(date)) schedulesDateCount[date] = 0; Will be: if(!schedulesDateCount.ContainsKey(date)) schedulesDateCount[date] = 0; Then it should work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.