问题
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