2013-07-09 13 views
3

我通過加入從多個表中獲取數據,並且我想將特定列值的數據分組,但是在group by語句後,我可以訪問我的別名及其屬性。我正在犯什麼錯誤?linq after groupby無法獲得列值

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

目前還不清楚你想要做什麼。一旦你分組了,序列中的每個元素都是一個組 - 'r'不再作爲範圍變量存在,只有'g',這個組......你完全忽略了。看起來你錯誤地理解了'group'子句的用途。 –

+0

但我無法訪問g變量的屬性 –

+0

如何使用g變量訪問該列 –

回答

3

你這樣做是錯誤的。正如Jon在將序列用別名rta分組後所說不存在。分組後,您將收到g的各個元素中的r,t,a的順序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(); 
+0

謝謝我會試試 –

+0

看看更新後的帖子,我添加了一些解釋。 – YD1m

+0

再次感謝朋友 –