I think I am coming closer to what I want but think I could use some help.
What I found out was if I do order.by(x => x.Datum)
the date gets sorted despite being a string by the format yyyy/MM/dd
so far so good, now I decided to extend the string to a daterange, like so: dd/MM/yyyy-dd/mm/yyyy
.
From my point of understanding, I can also convert the string to a datetime object with DateTime.ParseExact
but get the following error:
FormatException: DateTime pattern 'd' appears more than once with different values
Is it not possible to store a date range in a datetime
object?
public IActionResult Termin() //Diese Methode zeigt die Termine an.
{
var termin = _context.Termin
.Select(x => new ViewModelExposeTermin
{
Id = x.Id,
Name = x.Name,
Ort = x.Ort,
Datum = x.Datum,
Uhrzeit = x.Uhrzeit
})
.ToList()
.OrderBy(x => DateTime.ParseExact(x.Datum, "dd/MM/yyyy-dd/MM/yyyy", CultureInfo.CurrentCulture));
return View(termin);
}
I'm not sure that sql has a data-range like type, instead you could use 2 datetime fields.
public class TerminDatabaseModel
{
/*
* Some other properties
*/
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
Then you can create your own custom DateTimeRange
value type, it should implements IComparer<DateTimeRange>
in order to be used in OrderBy
by Linq.
public readonly struct DateTimeRange : IComparer<DateTimeRange>
{
public DateTimeRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
public DateTime Start { get; }
public DateTime End { get; }
public TimeSpan Duration => Start - End;
// comparing implementation
public int Compare(DateTimeRange x, DateTimeRange y)
{
return x.Duration.CompareTo(y.Duration);
}
/*
* Other stuff
*/
}
and add it to your ViewModel
public class ViewModelExposeTermin
{
/*
* Some other properties
*/
public DateTimeRange Datum { get; init; }
}
Finally, map the DateTime
fields to the DateTimeRange
field with
var termin = _context.Termin
.Select(x => new ViewModelExposeTermin
{
Id = x.Id,
Name = x.Name,
Ort = x.Ort,
Datum = new DateTimeRange(x.StartDateTime, x.EndDateTime),
Uhrzeit = x.Uhrzeit
})
.ToList()
.OrderBy(x => x.Datum);
return View(termin);
The order take place after the data are retrieved from the database. To perform the sort inside the query, you have to use EF's OrderBy
before fetching with ToList
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.