开发者

Splitting list by Date property in C# or using jQuery

I have a List<Event> and an Event has a Date property. I'm currently binding this list to an asp:repeater which is fine and results in a list of event titles like this:

event 1

event 2

event 3

event 4

event 5

However, now I wish to add some kind of separator to my list between events occurring on different days so that my list looks like:

Tuesday, May 10, 2011

event 1

event 2

Wednesday, May 11, 2011

event 3

Thursday, May 12, 2011

event 4

event 5

Can anyone recommend a go开发者_如何学Good way to do this. I'm happy to manipulate my list server-side or to bind my list and then add the separators client-side with jQuery. Any suggestions?


You can group by date server side using Linq's GroupBy

class Event
{
    public DateTime EventDate;
    public string EventName;
}

List<Event> events = GetEvents();

var grouped = events.GroupBy(e => e.EventDate.Date).OrderBy(g => g.Key);

foreach (var grouping in grouped)
{
    Console.WriteLine(grouping.Key); // <-- this is the date

    foreach (Event e in grouping) // <-- this is the list of events
    {
        Console.WriteLine(e.EventName); 
    }
}

GroupBy returns IEnumerable<IGrouping<TKey, TSource>>, so in this case you are returning IEnumerable<IGrouping<DateTime, Event>>


Or you can use nested repeaters - in this case you'll need two of them -.

Parent repeater render dates and nested one items for parent item's date.

It's all about setting Repeaters' data source in another way than current one and play with Repeater.ItemDataBound event.


You can group the events by day and use that key as a header of the repeater.


Another way:

List date = (From Event n in yourEventList
                      select new {n.Date}).ToList().Distinct();

foreach (DateTime dateA in date)
{
//add to the Date and then add the events does match with the date.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜