patterncsharpMinor
Using Linq to select the first and last values
Viewed 0 times
lastlinqthevaluesfirstusingandselect
Problem
I want to get just the first and last values in a date range. I have the following code:
This seems inefficient to me as I select the entire date range values initially. I can't seem to find a way to put first and last into the select command. Surely there must be a way to do this?
In response to Svick.
So, if I do this:
Is that the best way to do it? I don't have any profiling tools (or if I do, I'm unsure how to use them).
The solution as provided by svick is:
A lot of this comes from my lack of understanding of the difference between IQueryable, IEnumerable and List. Here is a good explanation that helped me understand a bit more of what's going on:
https://stackoverflow.com/questions/4844660/differences-between-iqueryable-list-ienumerator
using (var myEntities = new dataEntities())
{
var myValues = (from values in myEntities.PointValues
where values.PointID == dataValue && values.DataTime >= fromDate && values.DataTime { myValues.First(), myValues.Last() };
return myBarChart;
}This seems inefficient to me as I select the entire date range values initially. I can't seem to find a way to put first and last into the select command. Surely there must be a way to do this?
In response to Svick.
So, if I do this:
var firstValue = (from values in myEntities.PointValues
where values.PointID == dataValue && values.DataTime >= fromDate && values.DataTime = fromDate && values.DataTime <= toDate
orderby values.DataTime
select new BarChartValue
{
Time = values.DataTime,
Value = values.DataValue
}).Last();Is that the best way to do it? I don't have any profiling tools (or if I do, I'm unsure how to use them).
The solution as provided by svick is:
var myValues = (from values in myEntities.PointValues
where values.PointID == dataValue && values.DataTime >= fromDate && values.DataTime { myValues.First(), myValues.OrderByDescending(p => p.Time).First() };A lot of this comes from my lack of understanding of the difference between IQueryable, IEnumerable and List. Here is a good explanation that helped me understand a bit more of what's going on:
https://stackoverflow.com/questions/4844660/differences-between-iqueryable-list-ienumerator
Solution
What you could do is to remove the
ToList() from your query. This would change your code from making a single query that returns many values to two queries, each returning a single value.Context
StackExchange Code Review Q#25769, answer score: 4
Revisions (0)
No revisions yet.