Kalanamith
Kalanamith

Reputation: 20658

How to make the assigned values not getting changed after modifying the list used to assign

I have a list like this

List<Employees> elist = new List<Exployees>();

This has n number of records and I um declaring another fresh list and used following approaches

List<LateEmployees> lateList = new List<Employees>(elist);

and after that I m adjusting values in elist . After that I have seen the values in the lateList also got changed.

Then I used this approach

foreach(var entity in elist){
   lateList.Add(entity)
}

After changing the elist property values the same has happened all over again .

How do I prevent lateList getting changed after modifying the elist in C# 4.5

Upvotes: 0

Views: 51

Answers (1)

Andr&#233; Kops
Andr&#233; Kops

Reputation: 2713

Although lateList is a separate list, the items it contains are still the same employee objects. As such any change to those objects will happen in both lists. In other words, the only difference between the lists is which employees they contain, not the specifics of the employees.

In order to save the old versions of the employees to lateList you will need to copy each employee to a new Employee object - copying all the property values - and then add the copies to lateList.

e.g:

foreach (var entity in elist)
{
    lateList.Add(new Employee()
    {
        InTime = entity.InTime
        //Other properties too
    });
}

It is advisable to put the "new Employee() { }" stuff in a method (e.g. "Clone()" of Employee so you can reuse it later.

Upvotes: 1

Related Questions