【问题标题】:linq after groupby unable to get column valuesgroupby后的linq无法获取列值
【发布时间】:2013-07-09 04:51:05
【问题描述】:

我通过加入从多个表中获取数据,并且我想对特定列值的数据进行分组,但在 group by 语句之后,我可以访问我的别名及其属性。我犯了什么错误?

public List<PatientHistory> GetPatientHistory(long prid)
{
    using(var db = new bc_limsEntities())
    {
        List<PatientHistory> result = 
            (from r in db.dc_tresult
             join t in db.dc_tp_test on r.testid equals t.TestId into x
             from t in x.DefaultIfEmpty()
             join a in db.dc_tp_attributes on r.attributeid equals a.AttributeId into y
             from a in y.DefaultIfEmpty()
             where r.prid == prid
             group new {r,t,a} by new {r.testid} into g
             select new PatientHistory
             {
                 resultid = r.resultid,
                 bookingid = r.bookingid,
                 testid = r.testid,
                 prid = r.prid,
                 attributeid = r.attributeid,
                 result = r.result,
                 Test_Name = t.Test_Name,
                 Attribute_Name = a.Attribute_Name,
                 enteredon = r.enteredon,
                 Attribute_Type = a.Attribute_Type
             }).ToList();
        return result;
    }
}

【问题讨论】:

  • 不清楚您要做什么。分组后,序列的每个元素都是一个组 - r 不再作为范围变量存在,只有 g,组......您完全忽略了它。您似乎误解了group 子句的目的。
  • 但我无法使用 g 变量访问属性
  • 如何使用g变量访问列
  • 好吧,ggroup - 它是具有相同 testid 的所有记录,因为这就是您分组的依据...再次,真的不清楚是什么你正在努力实现
  • 我需要根据 testid 对我选择的列进行分组

标签: c# sql linq join group-by


【解决方案1】:

你这样做是错误的。正如 Jon 在使用别名 r,t,a 对序列进行分组后所说的那样,a 不存在。分组后,您会在g 的每个元素中收到序列rta 的序列g。如果您想从每个组中获取一个对象(例如最近的),您应该尝试以下操作:

List<PatientHistory> result = 
    (from r in db.dc_tresult
     join t in db.dc_tp_test on r.testid equals t.TestId into x
     from t in x.DefaultIfEmpty()
     join a in db.dc_tp_attributes on r.attributeid equals a.AttributeId into y
     from a in y.DefaultIfEmpty()
     where r.prid == prid
     group new {r,t,a} by new {r.testid} into g
     select new PatientHistory
     {
         resultid = g.Select(x => x.r.resultid).Last(), // if you expect single value get it with Single()
         // .... here add the rest properties
         Attribute_Type = g.Select(x => x.a.Attribute_Type).Last()
     }).ToList();

【讨论】:

  • 我应用了这个查询,但是当我在foreach循环中迭代获取结果时,出现连接超时异常,服务器很长时间没有响应,为什么会出现问题? @YD1m
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 2012-12-14
  • 2023-01-20
  • 1970-01-01
  • 2021-09-30
  • 2012-09-01
相关资源
最近更新 更多