Linq - Data Entities - Records by Max Date with CASE
I needed to get essentially a summary by case statement for a given date. As you can see I have defined the MAX date into a variable. This example also shows using a substring of the first character in a LET statement
DateTime? maxDate =
(from a in context.tbl_tslog
orderby a.CurrentTime
select (DateTime?) a.CurrentTime ).Max();
var dbRecords = (from c in context.tbl_testlog
where (c.CurrentTime >=maxDate)
let range = ( c.Usr.ToUpper().Substring(0,1) == "B" ? "US" :
c.Usr.ToUpper().Substring(0, 1) == "G" ? "CA" :
c.Usr.ToUpper().Substring(0, 1) == "U" ? "UK" : "Other"
)
group c by range into g
select new { Group = g.Key, Users = g.Count(), Latest = g.Max(c => c.CurrentTime) }).ToList();
The results bound to a grid look like this -
DateTime? maxDate =
(from a in context.tbl_tslog
orderby a.CurrentTime
select (DateTime?) a.CurrentTime ).Max();
var dbRecords = (from c in context.tbl_testlog
where (c.CurrentTime >=maxDate)
let range = ( c.Usr.ToUpper().Substring(0,1) == "B" ? "US" :
c.Usr.ToUpper().Substring(0, 1) == "G" ? "CA" :
c.Usr.ToUpper().Substring(0, 1) == "U" ? "UK" : "Other"
)
group c by range into g
select new { Group = g.Key, Users = g.Count(), Latest = g.Max(c => c.CurrentTime) }).ToList();
The results bound to a grid look like this -
Comments