显示分组依据中每个元素的 3 个结果
本文关键字:元素 结果 显示 | 更新日期: 2023-09-27 18:35:18
>我正在研究一个处理抄表的系统。
我想生成一个输出,其中系统显示属于客户的所有仪表,以及每个仪表的最后三个读数。
到目前为止,我必须编写以下代码:
var lastMeterReading = from meeters in metermodel.Meeters
join reading in metermodel.Readings on meeters.MeterNumber equals reading.MeterNumber
where (maalers.CustNo == 6085574)
orderby reading.Date descending
group meeters by new { meeters.MeterNumber, reading.Consumption, reading.Date } into result
select new
{
Consumption = result.Key.Consumption, No = result.Key.MeterNumber, Date = result.Key.Date
};
现在,它显示属于客户的所有仪表。如果我输入一个 .take(3),它只显示前 3 个结果。
感谢!丹尼尔
我认为您需要的是将.将(3)放在正确的位置。在你的情况下,你可能确实产生了结果。Take(3) 但这意味着取前三组(及其所有元素)。
下面试图说明我的意思,但是,我想您需要在最后一部分中修复它,因为我没有数据来测试它,因此我不确定我尝试访问的内容是否可以访问。但我希望你明白我的意思。
var lastMeterReading = (from meeters in metermodel.Meeters
join reading in metermodel.Readings on meeters.MeterNumber equals reading.MeterNumber
where (maalers.CustNo == 6085574)
orderby reading.Date descending
group meeters by new { meeters.MeterNumber, reading.Consumption, reading.Date } into result
from m in result
select new {Key = m.Key, Info = result.OrderByDescending(r => r.Date).Take(3)})
.Select(r => new
{ Consumption = r.Consumption, No = r.MeterNumber, Date = r.Date });
试试这个:
var lastMeterReading = from meeters in metermodel.Meeters
join reading in metermodel.Readings on meeters.MeterNumber equals reading.MeterNumber
where (maalers.CustNo == 6085574)
orderby reading.Date descending
group meeters by new { meeters.MeterNumber, reading.Consumption, reading.Date } into result
from m in result.Take(3)
select new
{
Consumption = m.Consumption, No = m.MeterNumber, Date = m.Date
};
您只想按 MeterNumber 分组。按照您现在进行分组的方式,您将为每个唯一的计量编号-消耗-日期组合获得一个新组。
还可以使用 LINQ 的 GroupJoin 运算符简化查询。在查询语法中,使用"join..上。。进入"模式:
from meter in meterModel.Meters
where (meter.CustNo == 6085574)
join reading in meterModel.Readings
on meter.MeterNumber equals reading.MeterNumber
into meterGroup
select meterGroup.OrderByDescending(r => r.Date).Take(3);
或使用点表示法:
meterModel.Meters
.Where(x => x.CustNo == 6085574)
.GroupJoin(
meterModel.Readings,
meter => meter.MeterNumber,
reading => reading.MeterNumber,
(meter,readings) => readings.OrderByDescending(r => r.Date).Take(3))
;