编辑 3:改进的问题措辞和示例
我有以下使用分组的 linq 查询。分组和选择操作很复杂,因此我将其中一个选择抽象为一种方法,该方法对如何呈现数据做出一些选择。
我的查询在匿名组定义中可以正常工作,但是一旦我将其键入一个类以便将其作为 IGrouping 对象传递给一个方法,它就会停止对结果进行分组。
public class TestController : Controller
{
public JsonResult ThisWorks()
{
var valueList = DataMocker.GetTestValues();
var group = from v in valueList.AsEnumerable()
where (v.Data != 0)
group v by new
{
Year = v.Fecha.Value.Year,
Trimester = string.Empty,
Month = v.Fecha.Value.Month,
Day = 0,
}
into g
select new SeriesDataPoint
{
y = g.OrderByDescending(obd => obd.Fecha)
.Select(obd => obd.Data.Value)
.FirstOrDefault(),
color = "black",
month = g.Key.Month,
year = g.Key.Year,
seriesName = "Test Series",
};
return Json(group, JsonRequestBehavior.AllowGet);
}
public JsonResult ThisDoesnt()
{
var valueList = DataMocker.GetTestValues();
var group = from v in valueList.AsEnumerable()
where (v.Data != 0)
group v by new Models.SeriesResultGroup
{
Year = v.Fecha.Value.Year,
Trimester = string.Empty,
Month = v.Fecha.Value.Month,
Day = 0,
}
into g
select new SeriesDataPoint
{
y = RenderDataPoint(valueList, g),
color = "black",
month = g.Key.Month,
year = g.Key.Year,
seriesName = "Test Series",
};
return Json(group, JsonRequestBehavior.AllowGet);
}
public static decimal? RenderDataPoint(List<Models.ValoresResultSet> valores, IGrouping<Models.SeriesResultGroup, Models.ValoresResultSet> group)
{
return group.OrderByDescending(obd => obd.Fecha)
.Select(obd => obd.Data.Value)
.FirstOrDefault();
}
}