C# unable to get value from lambda expression

Our company has purchased an app written in .NET and I have got a privilege to support it. I have never worked with .NET therefore I need some guidance with how to use lambda.

In my cshtml file I am trying to get a value and validate if it's NULL or not.

I have tried to do this like so

var appointment = x => x.AppointmentDate;

I receive compiler error "Cannot assign lambda expression to implicitly-typed local variable". I googled the error and tried the following.

Func<DateTime, DateTime> appointment = x => x.AppointmentDate;

However now compiler gives this error "'System.DateTime' does not contain a definition for 'AppointmentDate' and no extension method 'AppointmentDate' accepting a first argument of type 'System.DateTime' could be found (are you missing a using directive or an assembly reference?) "

How can I get a value to validate from lambda?

Jon Skeet
people
quotationmark

I think you're confused by what Func<T, TResult> is meant to be. The first parameter (T) is the input to the delegate; TResult is the output. So you probably want:

Func<Appointment, DateTime> appointmentFunction = x => x.AppointmentDate;

... where Appointment is the type of the object you're working with.

Of course, that won't check whether the value is null - and in fact if the AppointmentDate property is just DateTime then it can't be null, as DateTime is a non-nullable value type.

Note that in many cases you don't need to assign a lambda expression to a local variable - if you're calling a generic method, you can often let type inference work out the types for you. For example, if you have a List<Appointment> you could use:

var sorted = appointments.OrderBy(x => x.AppointmentDate);

and type inference would work out the delegate type you're interested in.

I would suggest that it's worth learning C# methodically though, rather than trying to learn it just through changes to an existing app. You could easily get into bad habits - and misunderstand fundamental language concepts - if you're not careful.

people

See more on this question at Stackoverflow