How to get copy of data instead of link using linq / lambda in C #?

Is there an easy way to just get a copy of the data instead of the link using this method? I tried .ToArray (). Where (), but it still looks like a link.

Example:

static void Main(string[] args) { List<ob> t = new List<ob>(); t.Add(new ob() { name = "hello" }); t.Add(new ob() { name = "test" }); ob item = t.Where(c => c.name == "hello").First(); // Changing the name of the item changes the original item in the list<> item.name = "burp"; foreach (ob i in t) { Console.WriteLine(i.name); } Console.ReadLine(); } public class ob { public string name; } 
+7
source share
4 answers

You need to create a copy of your ob yourself - this is not what LINQ provides.

+6
source

You can define the Clone method based on the existing protected MemberwiseClone method:

 public class Item { public Item Clone() { return (Item)this.MemberwiseClone(); } } 

Then:

 ob item = t.Where(c => c.name == "hello").First().Clone(); 
+3
source

Since ob is a class, it is a reference type , and therefore any instance of ob , if assigned to another variable (as happens on the line ob item = t.Where(c => c.name == "hello").First(); ) will automatically copy the link to the original instance, and not copy the actual instance itself. This is a common .NET theme regarding copying objects and apart from LINQ / Lambda,

To achieve what you want, you need to either create a Shallow Copy or Deep Copy of the resulting instance from your LINQ projection.

Shallow Copy is enough for your ob class (ShallowCopy usually copies as little as possible, while DeepCopy copies everything). A good link for the differences can be found here ).

To execute a ShallowCopy object, you can simply use MemberwiseClone , which is a built-in method of the .NET object type inherited by all objects.

For something more substantial, you will have to implement your own DeepCopy function, but it can be relatively simple. Something similar to these implementations, as indicated here and here .

+2
source

An easier way is to simply serialize your data in json and then again. It requires a small number of hits, but it is safer as it is less error prone and you do not need to modify all your classes.

just do:

 var json = JsonConvert.SerializeObject(myObject) var clone = JsonConvert.DeserializeObject<T>(json) 
0
source

All Articles