Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This for loop prints month before every individual event.
Eg:- January
Event1.
January
Event2
January
Event3
March
Event4
March
Event5

I want output like a month prints all events happening in that month.
Eg:- January
Event1
Event2
Event3

March
Event1
Event2

What I have tried:

@foreach (var item in Model)
{

@item.EventDate.ToString("MMMMMMMMMMMMMMMMM")



@Html.ActionLink(item.EventDate.ToShortDateString(), "TrackAttendance", new { id = item.ScheduledEventId })
}
Posted
Updated 12-Aug-16 14:35pm

1 solution

C#
class ModelItem
{
    public DateTime EventDate;
    public int ScheduledEventId;

    public ModelItem(DateTime date, int id)
    {
        EventDate = date;
        ScheduledEventId = id;
    }
}

public string GetEventStr()
{
    List<ModelItem> Model = new List<ModelItem>();
    Model.Add(new ModelItem(new DateTime(2016, 1, 1), 1));
    Model.Add(new ModelItem(new DateTime(2016, 1, 2), 2));
    Model.Add(new ModelItem(new DateTime(2016, 1, 3), 3));
    Model.Add(new ModelItem(new DateTime(2016, 3, 1), 1));
    Model.Add(new ModelItem(new DateTime(2016, 3, 2), 2));

    StringBuilder sb = new StringBuilder();

    int currentMonth = 0;
    bool isFirst = true;
    foreach (var item in Model)
    {
        if (item.EventDate.Month != currentMonth)
        {
            if (isFirst)
                isFirst = false;
            else
                sb.AppendLine("<br />");

            sb.AppendLine(item.EventDate.ToString("MMMM") + "<br />");

            currentMonth = item.EventDate.Month;
        }

        sb.AppendLine("Event" + item.ScheduledEventId + "<br />");
    }

    return sb.ToString();
}
 
Share this answer
 
v3
Comments
Priyanshu Patel 12-Aug-16 20:58pm    
I can't include that code in view of mvc
adriancs 12-Aug-16 21:43pm    
I have updated the answer which gives you a better hint. What you need to do is apply the logic in your mvc.
Priyanshu Patel 16-Aug-16 11:31am    
Yep, Thanks a lot for the help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900