显示组中每个元素的3个结果

时间:2012-05-25 20:14:45

标签: c# sql-server linq

我正在研究处理抄表的系统。

我想生成一个输出,系统显示属于客户和每个仪表的所有仪表,最后三个读数。

到目前为止,我必须遵循以下代码:

 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个结果。

THX! 丹尼尔

3 个答案:

答案 0 :(得分:0)

试试这个:

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
                       };

答案 1 :(得分:0)

我认为你需要的是将.Take(3)放在正确的位置。 在你的情况下,你可能做了结果。采取(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 });

答案 2 :(得分:0)

您只想按 MeterNumber 进行分组。您现在正在进行分组的方式,您将为每个独特的 MeterNumber-Consumption-Date 组合获得一个新组。

您还可以使用LINQ的GroupJoin运算符简化查询。在查询语法中,您使用“join..on..into”模式:

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))
    ;