LINQ GROUP BY and MAX()

26,527

Solution 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)}

Solution 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)}); 
Share:
26,527
Remo H. Jansen
Author by

Remo H. Jansen

Microsoft MVP, Web development engineer, open-source contributor, entrepreneur, technology lover, gamer, and Internet enthusiast. I'm an active member of the TypeScript community. I'm the organizer of the Dublin TypeScript Meetup and the creator of InversifyJS (inversion of control container for TypeScript applications). I also write a blog about TypeScript and other web technologies at blog.wolksoftware.com. I'm the author of www.learningtypescript.com & www.functionaltypescript.com published by Packt Publishing.

Updated on July 05, 2022

Comments

  • Remo H. Jansen
    Remo H. Jansen almost 2 years

    I'm trying to find out how to write an SQL sentence in LINQ but I can't find a way to do it for the moment, this is the SQL command:

    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
    

    Can someone help me witht he linq syntax please?

    **I'm trying this so far (thanks 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)
                }); 
    

    But I'm getting the following error:

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

  • Remo H. Jansen
    Remo H. Jansen about 12 years
    Thanks that looks really close, it is telling me that "can not resolve join method" do you know why could it be?
  • levi
    levi about 12 years
    Are you using entity framework? Are there connections between LinqToSql Classes?