gmail user
gmail user

Reputation: 2783

group by date in linq

I've a table with datetime null field in sql server. I'm trying to group the results based on the year in that field. But, when I wrote linq query, I didn't get intellisense for Year when I type that field. It only shows HasValue and Value. I think because it is converted nullable type. How do I do the grouping in this case?

Upvotes: 1

Views: 1070

Answers (2)

k.m
k.m

Reputation: 31454

Also, keep in mind accessing .Value property of your nullable type may throw InvalidOperationException when there's no value (as in - field is NULL in database).

In which case you can either filter out null values:

var filteredGroups = rows.Where(row => row.DateTimeField.HasValue)
                         .GroupBy(row => row.DateTimeField.Value.Year);

...or return null values aswell; say under some dummy key:

var nullValuesPresent = rows.GroupBy(row => row.DateTimeField.HasValue 
    ? row.DateTimeField.Value.Year : -1);

...which in the example above, will be grouped under -1 key (or whatever value you choose to represent non-existing year scenario).

Upvotes: 0

Matt Ellen
Matt Ellen

Reputation: 11592

You should group on the Year of the value of the Nullable<DateTime> so

group obj by obj.DateTimeField.Value.Year into g

Upvotes: 2

Related Questions