Splitting list of objects by DateTime property

Deadly 提交于 2019-12-12 05:26:47

问题


I'm building a booking system for cinemas(of course it's just small project for studies).

Here is my Showcase model:

public class ShowcaseModel
{
    public string objectId { get; set; }
    public string MovieId { get; set; }
    public int Auditorium { get; set; }

    public DateTime? StartDate { get; set; }
}

I want to display schedule in "per day" form. To achieve this i get all Showcases where DateTime is greater than today and put them into

List< ShowcaseModel >.

Now i don't know how to split this list(into separate lists) by day using StartDate property.

Is there any way to achieve this?

Thanks in advance.


回答1:


You can use GroupBy method:

List<ShowcaseModel> list = new List<ShowcaseModel>();
//...
var gooupByDay = list.GroupBy(o=>o.StartDate.Value.Date);



回答2:


I have used fixture (simply creates random instances of your class) to demonstrate how you can get a list of items per date.

var fixture = new Fixture();

IEnumerable<ShowcaseModel> showCaseModel = fixture.CreateMany<ShowcaseModel>();
IEnumerable<ShowcaseModel> futureShowCases = showCaseModel.Where(s => s.StartDate != null && s.StartDate > DateTime.Now);

// we know none of start dates are null
var groupedShowCases = futureShowCases.GroupBy(s => s.StartDate.Value.Date);

List<Tuple<DateTime, IEnumerable<ShowcaseModel>>> showCasesByDate = new List<Tuple<DateTime, IEnumerable<ShowcaseModel>>>();
foreach (var groupedShowCase in groupedShowCases)
{
    var key = groupedShowCase.Key;
    showCasesByDate.Add(Tuple.Create(key, groupedShowCase.ToList().AsEnumerable()));
}



回答3:


Using Linq GroupBy()

var grouped = list.Where(f=>f.StartDate!= null)
            .GroupBy(f => f.StartDate.Value.Date, b => b,
                               (k, g) => new { Date= k.Date, 
                                               Movies= g }).ToList();

Assuming list is a collection of your ShowCaseModel



来源:https://stackoverflow.com/questions/34407607/splitting-list-of-objects-by-datetime-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!