Evonet
Evonet

Reputation: 3640

Passing a parameter to a getter/setter

I have a class with a calculated parameter:

public class Job
{
    public Job()
    {            
        Reports = new List<Report>();
    }

    [Key]
    public int JobID { get; set; }

    public ICollection<Report> Reports { get; set; }
    public DateTime AppointmentDate { get; set; }

    public decimal AverageReportTurnaround
    {
        get
        {
            DateTime reportdate = Reports.Select(x=>x.DateCompleted).FirstOrDefault();

            return (reportdate - AppointmentDate).Value.Days;

        }
    }

How can I pass a datefrom field to the constructor so that it only calculates AverageReportTurnaround where the reportdate is > datefrom?

Upvotes: 1

Views: 1090

Answers (2)

Martin Vich
Martin Vich

Reputation: 1082

You can do this:

public class Job
{
public Job(DateTime dateFrom)
{            
    Reports = new List<Report>();
    DateFrom = dateFrom;
}

[Key]
public int JobID { get; set; }

public ICollection<Report> Reports { get; set; }
public DateTime AppointmentDate { get; set; }
public DateTime DateFrom { get; private set; }

public decimal AverageReportTurnaround
{
    get
    {
        DateTime reportdate = Reports.Where(x => x.ReportDate > DateFrom).Select(x=>x.DateCompleted).FirstOrDefault();

        return (reportdate - AppointmentDate).Value.Days;

    }
}

But if you're using this class in EntityFramework (judging from the 'Key' attribute) you should turn AverageReportTurnaround into a method with dateFrom as a param

Upvotes: 0

James
James

Reputation: 82096

You can use a private field

public class Job
{
    private DateTime fromDate;

    public Job(DateTime fromDate)
    {             
        Reports = new List<Report>();
        this.fromDate = fromDate;
    }
    ...
    public decimal AverageReportTurnaround
    {
        get
        {
            DateTime reportdate = Reports.Where(x => x.DateCompleted > this.fromDate)
                .Select(x=> x.DateCompleted).FirstOrDefault();
            return (reportdate - AppointmentDate).Value.Days;

        }
    }
}

Upvotes: 1

Related Questions