I have the following code, and trying to avoid code duplication
What I’d like to do is have a Custom Extension method say called “SelectGrouped”
that would accept a “Shift” object, and return the anonymous type (not sure if that possible)
var groupedFillingsCurrentShift = currentShift.FilingMeasurements
.Where(f => TimeSpan.Parse(f.MeasurementTime.MeasurementTime) == ShiftEnd)
.GroupBy(f => new { f.Medium, f.MeasurementTime })
.Select(t => new { t.Key.Medium, t.Key.MeasurementTime, VolumeInTanks = t.Sum(s => s.Filing) })
.ToList();
if (previousShift != null)
{
var groupedFillingsPreviousShift = previousShift.FilingMeasurements
.Where(f => TimeSpan.Parse(f.MeasurementTime.MeasurementTime) == previousShift.ShiftEnd)
.GroupBy(f => new { f.Medium, f.MeasurementTime })
.Select(t => new { t.Key.Medium, t.Key.MeasurementTime, VolumeInTanks = t.Sum(s => s.Filing) })
.ToList();
What I’d like to achieve is to have it look like so
var groupedResultCurrentShift =
currentShift.SelectGrouped(t=>t.Medium, t.MeasurementTime, t.VolumenInTanks);
var groupedResultPreviousShift =
previousShift.SelectGrouped(t=>t.Medium, t.MeasurementTime, t.VolumenInTanks);
Unfortunately, what you want can’t be done in its current form.
First off, the variable
tonly has value in the lambda. The commas separate parameters, and sotloses its scope for the other parameters.Second and more importantly, anonymous types are locally scoped by definition, because you have to use “var” to imply the type of a variable that holds them. You can’t pass them in as parameters nor return them as return values (well, technically you can using
dynamic, but let’s not go there, please).If you were to define a named type that could be used to hold the final form of the projected data, this would work: