0
public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string RestaurantName { get; set; }
}

List<UserModel> TempUserModelList = new List<Items>(OriginalList);

Now on editing an Item in TempUserModelList also changes the original values in OriginalList.

How do i copy values from the OriginalList into a temporary list so that the original list does not get changed ?

MainakChoudhury
  • 502
  • 1
  • 7
  • 23
  • Copy the objects. Create new objects containing the same data as the originals. A `class` is a reference type. That means there's only a single instance of the object and what gets passed around is a reference to that object. – Panagiotis Kanavos Nov 25 '21 at 12:41
  • Doe's this [answer](https://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c) of @ajm answered your question? – Bernana Nov 25 '21 at 12:42

3 Answers3

2

You could implement the ICloneable interface in your UserModel object

public class UserModel : ICloneable
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string RestaurantName { get; set; }

    public object Clone()
    {
        var clone = (UserModel)MemberwiseClone();
        return clone;
    }
}  

and then perform the copy like this:

List<UserModel> TempUserModelList = OriginalList.Select(s => (UserModel)s.Clone()).ToList();
John M
  • 2,510
  • 6
  • 23
  • 31
0

My recommendation would be to avoid mutable objects and instead embrace immutability. I.e. make all properties of the class read only. This makes it much easier to reason about objects, and you never have to worry about objects changing. See this answer for more details about the benefit of immutability.

Record types in c# 9 makes this fairly easy, allowing you to write:

TempUserModelList[0] = TempUserModelList[0] with { FirstName = "MyNewName"};

c# 10 allows the same with syntax to be used for structs and anonymous types. While this is slightly more to write than just mutating the property, the benefits often outweigh the cost in my opinion.

A potential problem is that this model may not work very well in WPF where properties need to have setters.

JonasH
  • 28,608
  • 2
  • 10
  • 23
0

For a quick solution without changing object type (mostly for simple dtos) using System.Text.Json:

public class Program
{
    var orgList = new List<UserModel>()
    {
        new UserModel(){FirstName = "Jan"},
        new UserModel(){FirstName = "Tom"},
        new UserModel(){FirstName = "Alan"}
    };

    List<UserModel> TempUserModelList = new List<UserModel>();
    foreach (var user in orgList)
    {
        var copyUser = JsonSerializer.Deserialize<UserModel>(JsonSerializer.Serialize(user));
        TempUserModelList.Add(copyUser);
    }
}

TempUserModelList will contain new set of copied users.

quain
  • 861
  • 5
  • 18