Home > Back-end >  C# Change selected object from a list without changing the original list
C# Change selected object from a list without changing the original list

Time:10-05

Here I've selected the record which a want to get into a new variable. and after that, when I'm changing the value of 'itm.note' it's automatically modifying the original list (Obj.Testlist) as well. How can this be avoided? Only want to change 'itm' object and Obj.Testlist list should be keep as it is.

var itm = Obj.Testlist.Where(x => x.id == 1).SingleOrDefault();

itm.note = "text";

CodePudding user response:

You could clone the fetched item, but that wouldn't be efficient.

How about this:

var changedFetchedItem = Obj.Testlist.Where(x => x.id == 1)
    .Select(x => new
    {
        Id = 1,
        Note = "text",

        // copy the other properties that you plan to use
        // don't copy the ones that you don't use.
    }
    .SingleOrDefault();

Since you will be fetching at utmost one item, this is very efficient.

I chose to create an object with anonymous type. If you need a specific type, you can add the type after the keyword new

CodePudding user response:

Since I have large model, decided to use cloning for this (Sample code),

public class TestClone : ICloneable
    {
        public bool IsSuccess { get; set; }
        public string Note { get; set; }
        public string ErrorDetail { get; set; }

        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }

    static void Main(string[] args)
    {
        var test1 = new TestClone() { IsSuccess = true, Note= "text", ErrorDetail = "DTL1" };
        var test2 = (TestClone) test1.Clone();
        test2.Note= "new text";
    }
  • Related