LINQ left join with only the row having maximum value of a column
You can do it many ways. One of those way is:
var result = (from pi in projectInformations join pu in projectUpdates on pi.ProjectID equals pu.ProjectID into tpu from t in tpu.OrderByDescending(c => c.CreateDate).Take(1) select new { pi.ProjectID, pi.DataA, t.CreateDate, t.DataB }).ToList();
You can use a one to many association from ProjectInformation to ProjectUpdate and OrderByDescending/FirstOrDefault.
public class ProjectInformation { public int ProjectID { get; set; } public virtual ICollection<ProjectUpdate> ProjectUpdates { get; set; }}db.Project .Select(p => new { ProjectID = p.ProjectID, MostRecentProjectUpdate = p.ProjectUpdates.OrderByDescending(u => u.CreateDate).FirstOrDefault()});
Note: Using OrderByDescending may be tricky if CreateDate is a string rather than a Date in your database.
Try this:-
var result = (from pi in projectInfo join pu in projectupdates on pi.ProjectID equals pu.ProjectID into g let data = g.OrderByDescending(x => DateTime.ParseExact(x.CreateDate, "dd/M/yyyy", CultureInfo.InvariantCulture)).FirstOrDefault() select new { ProjectID = data.ProjectID, CreatedDate = data.CreateDate, DataA = pi.DataA, DataB = data.DataB }).ToList();
Please note, Since I am using FirstOrDefault
you need to check if data is not null before accessing its properties.