BviLLe_Kid BviLLe_Kid -4 years ago 78
C# Question

Access to new class object's properties

If I am creating a new class object and assigning its properties values like so:

foreach (var item in lstOfPersonnel)
{
ClassNameVM personVM = new ClassNameVM ()
{
Name = item.FirstName + " " + item.LastName,
TimeTotalPFID = lstSummaries.Where(x => x.PFID == item.ID).Sum(x => x.Time),
TimeTotalPNFID = lstSummaries.Where(x => x.PNFID == item.ID).Sum(x => x.Time),
TimeTotalVO = lstSummaries.Where(x => x.VO == item.ID).Sum(x => x.Time),
TotalTime = // trying to do TimeTotalPFID + TimeTotalPNFID + TimeTotalVO.. but I can't access those properties.
};

newListPersonnel.Add(personVM);
}


How do I access the
TimeTotalPFID
,
TimeTotalPNFID
,
TimeTotalVO
properties within the object itself?

Answer Source

In this case if you want the total time to just be the sum of other properties then don't work it out each time. This is error prone and doesn't respond correctly if the other properties change. Best in this case is to just have a property that only has a get which does the calculation for you...

public class ClassNameVM
{
    /*other properties as normal */
    public int TotalTime
    {
        get { return TimeTotalPFID + TimeTotalPNFID + TimeTotalVO; }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download