How to keep a Generic list unmodified when its copy is modified?

Posted by user1801934 on Stack Overflow See other posts from Stack Overflow or by user1801934
Published on 2012-11-06T04:00:42Z Indexed on 2012/11/06 5:00 UTC
Read the original article Hit count: 187

Filed under:
|

When I create a copy of the original list lstStudent in lstCopy and send the lstCopy to modification function, the lstStudent also gets modified. I want to keep this list unmodified.

List<Student> lstStudent = new List<Student>();
Student s = new Student();
s.Name = "Akash";
s.ID = "1";
lstStudent.Add(s);
List<Student> lstCopy = new List<Student>(lstStudent);
Logic.ModifyList(lstCopy);
// "Want to use lstStudent(original list) for rest part of the code"

public static void ModifyList(List<Student> lstIntegers) { 
    foreach (Student s in lstIntegers) { 
        if (s.ID.Equals("1")) { 
            s.ID = "4"; s.Name = "APS"; 
        } 
    } 
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about list