I have a list in c# :
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
List<Item> items = new List<Item>()
{
new Item() { Id = 1, Name = "Item-1" },
new Item() { Id = 2, Name = "Item-2" },
new Item() { Id = 3, Name = "Item-3" },
new Item() { Id = 4, Name = "Item-4" },
new Item() { Id = 5, Name = "Item-5" },
};
Now i use where clause on the above list of items and fetch all items whose Id is greater than or equals to 3.
List<Item> itemsWithIdGreaterThan3 = items.Where(i => i.Id >= 3).ToList();
The above statement creates a new List but it copies the objects by reference, so if i change any object`s property in itemsWithIdGreaterThan3 list then it reflect the changes in item list:
itemsWithIdGreaterThan3[0].Name = "change-item-2"
This also changes the object with Id = 3 in items List.
Now what i want is to clone the object, so i found Select function like:
List<Item> itemsWithIdGreaterThan3 = items.Where(i => i.Id >= 3)
.Select(i => new Item() { Id = i.Id, Name = i.Name }).ToList();
This works, but what if i have an object contains 20 to 30 properties or even more. Then in than case we have to manually copy each property. Is there any shortcut solution for this problem ??