【问题标题】:LINQ GROUP BY and MAX()LINQ GROUP BY 和 MAX()
【发布时间】:2012-04-10 09:11:11
【问题描述】:

我正在尝试找出如何在 LINQ 中编写 SQL 语句,但暂时找不到方法,这是 SQL 命令:

SELECT cs.Site_Name, MAX(ed.EffectiveDate_Date)
FROM [WAPMaster].[Factsheets].[EffectiveDate] ed,
[WAPMaster].[Configuration].[Site] cs
WHERE cs.Site_Id = ed.EffectiveDate_SiteId
GROUP BY cs.Site_Name

有人可以帮我了解一下 linq 语法吗?

**到目前为止我正在尝试这个(感谢 levanlevi)

var test = (from e in this._wapDatabase.EffectiveDates
            join c in this._wapDatabase.Sites 
            on c.Site_Id equals e.EffectiveDate_SiteId
            group e by c.Site_Name into r
            select new
            {
                r.Key.SiteName,
                EffectiveDate = r.Max(d => d.EffectiveDate_Date)
            }); 

但我收到以下错误:

http://i.stack.imgur.com/AkJ5V.png

【问题讨论】:

  • 请注意:没有任何将 快速已经工作 SQL 查询转换为 LINQ 的感觉。只需使用 SQL。 Linq 不是更好

标签: c# sql linq group-by max


【解决方案1】:
SELECT  cs.Site_Name ,
        MAX(ed.EffectiveDate_Date)
FROM    [WAPMaster].[Factsheets].[EffectiveDate] ed ,
        [WAPMaster].[Configuration].[Site] cs
WHERE   cs.Site_Id = ed.EffectiveDate_SiteId
GROUP BY cs.Site_Name



from e in WAPMaster.Factsheets.EffectiveDate
join c in WAPMaster.Configuration.Site
on c.Site_Id equals e.EffectiveDate_SiteId
group e by c.Site_Name into r
select new { SiteName = r.Key, EffectiveDate = r.Max(d=>d.EffectiveDate_Date)}

【讨论】:

  • 谢谢,看起来很接近,它告诉我“无法解析连接方法”你知道为什么会这样吗?
  • 你在使用实体框架吗? LinqToSql 类之间有联系吗?
【解决方案2】:
var test = (from effectiveDates in this._wapDatabase.EffectiveDates                         
            from sites in this._wapDatabase.Sites                         
            where sites.Site_Id = effectiveDates.EffectiveDate_SiteId
                     group effectiveDates by sites.Site_Id into g                         
             select new {  siteId = g.key , effectiveDate = g.max(ed => ed.EffectiveDate_Date)}); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2010-11-20
    • 2012-10-30
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多