Ronald S. Cook said:
Does anyone know how I would write this SQL in LINQ:
SELECT DepartmentId,
MAX(EmployeeHireDate)
FROM Employee
GROUP BY DepartmentId
Here's a sample for LINQ to Objects. I don't know what SQL it would
turn into with LINQ to SQL, but I think it does what you expect
using System;
using System.Linq;
class Employee
{
public DateTime EmployeeHireDate { get; private set; }
public string Name { get; private set; }
public string DepartmentId { get; private set; }
public Employee (string name, string department, int day)
{
Name = name;
DepartmentId = department;
EmployeeHireDate = new DateTime(2008, 1, day);
}
}
class Test
{
static void Main()
{
var employees = new[]
{
new Employee("Jon", "Dev", 1),
new Employee("Emma", "Dev", 3),
new Employee("Sally", "Sales", 2),
new Employee("Sarah", "Sales", 8),
new Employee("Russell", "Dev", 2),
new Employee("Mark", "Marketing", 10),
new Employee("Mary", "Marketing", 5)
};
var query = from employee in employees
group employee by employee.DepartmentId into
department
select new { Dept = department.Key,
MaxDate = department.Max
(emp => emp.EmployeeHireDate) };
foreach (var entry in query)
{
Console.WriteLine(entry);
}
}
}