user1017882
user1017882

Reputation:

How is the changing of one list affecting a completely different list?

I have the following code:

jobsToShiftUp.AddRange(PresentationManager.Instance.ScheduleViewSource.Where(o => o.Resources.First().ResourceName == criticalJob.Resources.First().ResourceName && ((o.Start >= criticalJob.Start) || (o.Start < criticalJob.Start && o.End > criticalJob.Start)) && !o.JobGuid.Equals(((Job)state.DraggedAppointments.First()).JobGuid) && GetWeekNumber(o.Start) == GetWeekNumber(criticalJob.Start)));
jobsToShiftUp = jobsToShiftUp.OrderBy(o => o.Start).ToList();
TimeSpan timeToShift = criticalJob.End - jobsToShiftUp.First().Start;

foreach (Job job in jobsToShiftUp)
{
    if (jobsToShiftUp.IndexOf(job) == 0)
    {
        ((ObservableCollection<Job>)state.DestinationAppointmentsSource).Single(o => o.JobGuid.Equals(job.JobGuid)).Start += timeToShift;
        ((ObservableCollection<Job>)state.DestinationAppointmentsSource).Single(o => o.JobGuid.Equals(job.JobGuid)).End += timeToShift;

......

The last two lines (increasing the start and end properties of the jobs) affects both the state.destinationappointmentssource list AND the jobsToShiftUp list (i.e. it affects the job object currently being referenced in the foreach loop). I can't think why it would affect the jobsToShiftUp list at all!?

Upvotes: 1

Views: 138

Answers (2)

ratneshsinghparihar
ratneshsinghparihar

Reputation: 301

I think both object have same reference.

So jobsToShiftUp collection and state.DestinationAppointmentsSource might both have some same reference and updating the one reflecting in another.

You can use cloning (deep copy) to avoid this .

Upvotes: 0

L.B
L.B

Reputation: 116138

Since both list contain the same instances of objects. Like:

Job job = new Job();
List<Job> list1 = new List<Job>{job};
List<Job> list2 = new List<Job>{job};

list[0].Start+=10 will add 10 to job which is also referenced by list2

Upvotes: 3

Related Questions