使用linq从组中选择列

时间:2013-08-29 14:41:54

标签: c# linq

LinqToSQL我在从组中选择列时遇到问题,下面是我的查询

var qry = (from i in INTERNETDATAs 
join c in COVERS on Convert.ToInt32(i.COVERTYPE) equals c.COV_TYPE
join b in BENEFITS on c.COVERID equals b.COVERID
join p in POLICies on i.REFERENCENO equals p.BACS_POLNO into grp
    where  i.DATELOADED >= new DateTime(2013,1,1)
    && i.DATELOADED < new DateTime(2014,1,1)
    && i.CAMPAIGNTYPE == "1"
    && c.COVERTYPEID == 17063789
orderby i.DOB   
select new
{
    i.ID,
    Campaign = i.CAMPAIGNTYPE,
    Title = i.TITLE,
    Dob = i.DOB,
    Accepted = i.ACCEPTED,
    BankLetter = i.BANKLETTER,
    //p.STATUS,
    //grp.STATUS,
    MonthlyPremium = c.MONTHLYPREMIUM,
    BenefitAmount = b.BENEFITAMOUNT,
    Description = b.BENEFITDESCRIPTION
}
).DefaultIfEmpty();         

 qry.Dump();

此查询提供了预期结果,但我还需要STATUS表中的POLICies列,当我删除//p.STATUS//grp.STATUS的评论时,我会得到以下错误,如下所示

无法执行文字选择:

  

'System.Collections.Generic.IEnumerable'没有   包含'STATUS'的定义,没有扩展方法'STATUS'   接受第一个类型的参数   'System.Collections.Generic.IEnumerable'可以   找到(按F4添加using指令或程序集引用)

如果有任何人可以帮我解决这个问题,因为我已尽力而为。

谢谢

1 个答案:

答案 0 :(得分:0)

您是POLICIES字段加入BACS_POLNO组,在SQL中将其视为group by。在最终选择器中,grp实际上是分组项的集合,并且每个项都可能具有不同的BACS_POLNO值。

如果要为每个不同的BACS_POLNO生成单独的项目,请执行常规联接:

join p in POLICies on i.REFERENCENO equals p.BACS_POLNO

或者,您可以从分组集合中选择第一个BACS_POLNO

var qry = (from i in INTERNETDATAs 
join c in COVERS on Convert.ToInt32(i.COVERTYPE) equals c.COV_TYPE
join b in BENEFITS on c.COVERID equals b.COVERID
join p in POLICies on i.REFERENCENO equals p.BACS_POLNO into grp
    where  i.DATELOADED >= new DateTime(2013,1,1)
    && i.DATELOADED < new DateTime(2014,1,1)
    && i.CAMPAIGNTYPE == "1"
    && c.COVERTYPEID == 17063789
orderby i.DOB   
select new
{
    i.ID,
    Campaign = i.CAMPAIGNTYPE,
    Title = i.TITLE,
    Dob = i.DOB,
    Accepted = i.ACCEPTED,
    BankLetter = i.BANKLETTER,
    grp.First().STATUS,
    MonthlyPremium = c.MONTHLYPREMIUM,
    BenefitAmount = b.BENEFITAMOUNT,
    Description = b.BENEFITDESCRIPTION
}
).DefaultIfEmpty();