c# - Linq ForEach() not populating fields -
i'm having trouble trying calculate 3 fields on model using foreach()
, linq. query returns "activities" specific issue. 1 of fields "timespent", long
. it's time spent on item in milliseconds. i'm trying show days, hours, , minutes based on "timespent" field, each activity. here's model:
public class activitygridmodel { public datetime activitydate { get; set; } public string activitytype { get; set; } public string notes { get; set; } public string enteredby { get; set; } public long timespent { get; set; } public int days { get; set; } public int hours { get; set; } public int minutes { get; set; } }
this query built:
var activities = in session.context.activities join @ in session.context.activitytypes on a.activitytypeid equals at.activitytypeid join u in session.context.users on a.createdbyuserid equals u.userid a.issueid == issueid select new activitygridmodel() { activitydate = a.activitydate, activitytype = at.activitytype1, notes = a.notes, enteredby = u.firstname + " " + u.lastname, timespent = a.timespent };
and here's try populate days, hours, , minutes of model:
activities.tolist().foreach(a => { timespan timespent = new timespan(a.timespent); a.days = timespent.days; a.hours = timespent.hours; a.minutes = timespent.minutes; }); return activities.tolist();
i other fields in results days, hours, , minutes 0. i'm not sure i'm doing wrong. appreciated.
this wrong in every sense. days, hours , minutes have read properties calculate value timespent internally. way you've implemented can end invalid data in objet. exapmle:
var model = new activitygridmodel { timespent = x }; model.days = 5; model.hours = 10;
is valid ?
a better approach computing days, hours , minutes internally:
public class activitygridmodel { public datetime activitydate { get; set; } public string activitytype { get; set; } public string notes { get; set; } public string enteredby { get; set; } private long _timespent; public long timespent { { return _timespent; } set { _timespent = value; var tsspent = new timespan(_timespent); days = tsspent .days; hours = tsspent .hours; minutes = tsspent .minutes; } } public int days { get; private set; //readonly class clients } public int hours { get; private set; //readonly class clients} public int minutes { get; private set; //readonly class clients} }
Comments
Post a Comment