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 ?
CodePudding user response:
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();
CodePudding user response:
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.
CodePudding user response:
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.