编程语言
首页 > 编程语言> > c#-groupby后的linq无法获取列值

c#-groupby后的linq无法获取列值

作者:互联网

我正在通过联接从多个表中获取数据,我想将特定列值上的数据分组,但是在按语句分组之后,我可以访问我的别名及其属性.我在犯什么错误?

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,t,a对序列进行分组之后,它不存在.分组后,您将在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();

标签:join,linq,sql,c,group-by
来源: https://codeday.me/bug/20191123/2064698.html