How to order a list by property and group elements in HTML Razor?

Maybe the question is difficult to explain, but here is the problem that I encountered, I have a list of model properties

public class ViewModel { public int PropertyID {get;set;} public DateTime Datefield {get;set} public string OtherProperty {get;set;} } 

Then I populate the list with some values:

 List<ViewModel> listOfValues = new List<ViewModel>(); listOfValues.Add(new ViewModel{ PropertyID = 1, Datefield = new DateTime(2010, 5,25, 12,00,00), OtherProperty = "Name1" }); 

Imagine the date field has the following meanings:

 0: 25/05/2010 12:00:00 1: 25/05/2010 12:00:00 2: 26/05/2010 13:00:00 3: 26/05/2010 13:00:00 4: 26/05/2010 14:00:00 5: 27/05/2010 12:00:00 

After that, I order a list with a simple listOfElements.OrderBy(o => o.Datefield).ThenBy(o => o.Datefield.Hour); to sort the list first by date, and after the date of the last hour.

Everything works fine, but then you need to β€œgroup” the elements by date and time, but not with GroupBy LINQ, but with RAZOR this way:

  <div> @Model.listOfElements[i].Datefield //0: 25/05/2010 12:00:00 @Model.listOfElements[i].Datefield //1: 25/05/2010 12:00:00 </div> <div> @Model.listOfElements[i].Datefield //2: 26/05/2010 13:00:00 @Model.listOfElements[i].Datefield //3: 26/05/2010 13:00:00 </div> <div> @Model.listOfElements[i].Datefield //4: 26/05/2010 14:00:00 </div> <div> @Model.listOfElements[i].Datefield //5: 27/05/2010 12:00:00 </div> 

I wanted to group them by date and time in html, so those that correspond, for example, in a div, so I can give them a style that is a kind of group. I tried with some ugly razor-html syntax, but I don't think this is the best way.

Hope the question is clear.

+6
source share
1 answer

Assuming that according to your code, which Model.listOfElements contains an IEnumerable<ViewModel> , you can use Linq to group dates, and then each group will contain a list of elements in that date group. To get a Date + Hour grouping, use the anonymous projection in the Group to simply view the date and time in the grouping

 @foreach (var grp in Model.listOfElements .OrderBy(m => m.PropertyID) .GroupBy(m => string.Format("{0:yyyyMMddHH}", m.Datefield))) { <div> @foreach (var itm in grp) { <p>@itm.PropertyID - @itm.Datefield</p> } </div> } 

Pre-ordering on the PropertyID will result in a grouping to indicate the order you specified. I added the PropertyID to the output for demonstration only - you can delete it as soon as the ordering is confirmed.

+5
source

Source: https://habr.com/ru/post/988059/


All Articles