c # directive for linq

0

I'm implementing a function that brings me the different years of a set of dates and I use linq, it's something like this:

var uniqueYears = Entidades.Ventas.Select(s => s.Fecha.Year).Distinct();

Send me an error in .Year

I am using the linq directive. Any suggestions?

Greetings.

    
asked by Monet 21.11.2018 в 13:29
source

1 answer

3

The problem may be that Fecha is Nullable<> or it may be null. Before using the Fecha you must validate with the property HasValue of the class Nullable if it contains information or not.

Try this code:

var uniqueYears = Entidades.Ventas.Where(s => s.Fecha.HasValue).Select(s => s.Fecha.Value.Year).Distinct();

First, all the dates that are not null are filtered (where) and then you end up selecting the list of dates to obtain the year.

Documentation of Nullable

    
answered by 21.11.2018 в 14:05