John Soer
John Soer

Reputation: 551

Lambda expression will not compile

I am very confused.

I have this lambda expression:

tvPatientPrecriptionsEntities.Sort((p1, p2) =>
    p1.MedicationStartDate
      .Value
      .CompareTo(p2.MedicationStartDate.Value));

Visual Studio will not compile it and complains about syntax.

I converted the lamba expression to an anonymous delegate as so:

tvPatientPrecriptionsEntities.Sort(
  delegate(PatientPrecriptionsEntity p1, PatientPrecriptionsEntity p2) 
  {
      return p1.MedicationStartDate
               .Value
               .CompareTo(p2.MedicationStartDate.Value);
  });

and it works fine.

The project uses .NET 3.5 and I have a reference to System.Linq.

Upvotes: 2

Views: 331

Answers (2)

BlueMonkMN
BlueMonkMN

Reputation: 25601

The following code compiles fine for me. Perhaps you should narrow down what significant differences exist between your code, and this simple example to pin down the source of the problem.

static void Main(string[] args)
{
   PatientPrescriptionsEntity[] ppe = new PatientPrescriptionsEntity[] {};
   Array.Sort<PatientPrescriptionsEntity>(ppe, (p1, p2) => 
       p1.MedicationStartDate.Value.CompareTo(p2.MedicationStartDate.Value));
}
...
class PatientPrescriptionsEntity
{
   public DateTime? MedicationStartDate;
}

Upvotes: 1

Oliver Mellet
Oliver Mellet

Reputation: 2387

DateTime.CompareTo is overloaded. Try using explicit parameter types in your lambda:

(DateTime p1, DateTime p2) => ...

Upvotes: 2

Related Questions