patterncsharpModerate
Sorting a list based on date and time
Viewed 0 times
sortingdatetimebasedandlist
Problem
I have a class that is used to basically store samples from data being read from a system. Within that class is a property that I use to store the date and time of that sample:
I need to sort a list of
This is what I've come up with:
The code seems to work, when I pass in a list of
public class ReadingValue
{
public DateTime DateTimeOfReading { get; set; }
public float Reading { get; set; }
}I need to sort a list of
ReadingValue based on the DateTimeOfReading property.This is what I've come up with:
public IEnumerable Hourly(IList readings)
{
var sortedReadings = readings.OrderBy(x => x.DateTimeOfReading.TimeOfDay)
.OrderBy(x => x.DateTimeOfReading.Date)
.OrderBy(x => x.DateTimeOfReading.Year);
return sortedReadings;
}The code seems to work, when I pass in a list of
ReadingValue's it returns the list in sorted order. Is there anything I've overlooked or should do differently? I know time and date programming can be a tricky topic with things like timezones, daylight savings etc. but sorting dates and times shouldn't involve any of that, I don't think.Solution
You should first do
OrderBy and then you should do ThenBy instead of doing another OrderBy. What you are currently doing is that you are re-ordering everything after your first OrderBy.public IEnumerable Hourly(IList readings)
{
var sortedReadings = readings.OrderBy(x => x.DateTimeOfReading.TimeOfDay)
.ThenBy(x => x.DateTimeOfReading.Date)
.ThenBy(x => x.DateTimeOfReading.Year);
return sortedReadings;
}Code Snippets
public IEnumerable<ReadingValue> Hourly(IList<ReadingValue> readings)
{
var sortedReadings = readings.OrderBy(x => x.DateTimeOfReading.TimeOfDay)
.ThenBy(x => x.DateTimeOfReading.Date)
.ThenBy(x => x.DateTimeOfReading.Year);
return sortedReadings;
}Context
StackExchange Code Review Q#112142, answer score: 11
Revisions (0)
No revisions yet.