【问题标题】:How to query the average from a certain property in an Entity and return it in a List of List of objects in LINQ?如何查询实体中某个属性的平均值并将其返回到 LINQ 中的对象列表列表中?
【发布时间】:2013-04-17 22:45:35
【问题描述】:

我在 Entity Framework 中设计的实体如下所示:

事件

  • EventId
  • 日期
  • 加速
  • 强度
  • 设备ID
  • 区块ID
  • 设备
  • 阻止

阻止

  • 区块ID
  • 开始日期
  • 日期结束
  • 活动

设备

  • 设备ID
  • 别名
  • 集群 ID
  • 集群
  • 活动

集群

  • 集群 ID
  • 姓名
  • 设备
  • 区域标识

地区

  • 区域标识
  • 姓名
  • 集群

一个事件属于一个块并由一个设备注册。一个Device属于一个Cluster,一个Cluster属于一个Region。

我要做的是获取块中事件的平均加速度和平均强度,组织在列表中的对象中,这些对象必须根据我是否想获得事件的平均值来组织每个集群或每个区域中的设备检测到的块。

我应该在 LINQ 中使用哪种查询?

为了更清楚,这些是代表我要执行的操作的 SQL 字符串

select avg(e.Intensity) as average from blocks b, events e, devices d, clusters c, regions r where b.blockid = 1 and b.blockid = e.blockid and e.uniqueid= d.uniqueid and d.clusterid  = c.clusterid group by c.clusterid;

select avg(e.Intensity) as average from blocks b, events e, devices d, clusters c, regions r where b.blockid = 1 and b.blockid = e.blockid and e.uniqueid= d.uniqueid and d.clusterid  = c.clusterid and c.regionid = r.regionid group by c.regionid;

【问题讨论】:

    标签: c# linq linq-to-sql average


    【解决方案1】:

    可能是这样的(linq to entity)...

    from ev in db.Events
    where ev.Block.BlockID == 1
    group ev by ev.Device.Cluster.Region.ID into g
    // group ev by ev.Device.Cluster.ClusterID into g
    select new
    {
        RegionID = g.Key, // ClusterID = g.Key,
        AverageIntensity = g.Average(x => x.Intensity),
        AverageAcceleration = g.Average(x => x.Acceleration),
    };
    

    添加其他字段,例如名称:

    group ev by new { ID = ev.Device.Cluster.ClusterID, Name = ev.Device.Cluster.Name } 
    into g  
    

    group ev by ev.Device.Cluster into g  
    // ...
    ClusterName = g.Key.Name,
    

    (两者的 SQL 相同)

    您有效地“按”多个字段进行“分组” - 但因为所有字段都相同 (即,如果 ID 相同,则名称相同)-您不会更改 分组的性质 - 您只需附加额外的字段。

    通常(无聚合)您也可以将“分组”添加到选择 Group = g,,然后展平并返回所有记录等。

    【讨论】:

    • 太好了,这就是我要找的,非常感谢。只是一个简单的问题,如果我将 Region 或 Cluster 的名称添加到结果中,我应该怎么做?我试过Name=g.Select(x=>x.Device.Cluster.Name),但返回集群/区域名称的次数与该集群或区域中分组的事件一样多。
    猜你喜欢
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多