Sample in C# and VB.NET are OK.
I have a table “People” with the following columns:
-FullName (nvarchar not null)
-DOB (datetime null)
I want to write a LINQ to SQL to group the people by age, like following result:
Age 19: 4 ppl
Age 20: 5 ppl
Age 21: 6 ppl
and so on…
Here’s my try:
Dim query = From ppl In db.People _
Select New With {.Age = DateTime.Now.Year - CDate(ppl.DOB).Year, .CountAge = ppl.Count}
Notice that there are no DOB record for some people in the tables, so these shall not be included. The DOB column has record like this 1982-10-24 10:12:45 AM because it’s a DateTime column.
I would rather:
We are grouping against year of birth here. This should translate to
GROUP BY YEAR(dob)in SQL which could have slightly better performance or optimization compared toGROUP BY YEAR(GETDATE()) - YEAR(dob). It’s almost impossible to map row expressions into indexes but certain constructs likeYEAR()alone could be optimized to use a datetime index partially. I make many assumptions here though, like thatdatetimestructures start with year, SQL server cares aboutYEAR(x)for optimizations etc. It’s still good to keep in mind such situations when constructing a LINQ query.