简体   繁体   中英

C# Editing items of two lists with same references

I have a List of myClass objects (some elements are added before)

List<myClass> myClassList1;

Then I copy some of the elements in this list into another list

List<myClass> myClassList2 = new List<myClass>();
foreach (myClass obj in myClassList1)
{
  myClassList2.Add(obj);
}

This list is now sorted

myClassList2.sort();

And then I want to modify the first element in this sorted list

myClassList2[0].id++;

Problem: in the myClassList2 this element is modified, but not in myClassList1 .

I thought adding myClass objects to a list will add a reference to this object, so i can modify it in the list (this was the actual plan).

It does update myClassList1 as you expect. You might want to post your code. Here's my code that updates both lists.

    public class myClass
    {
        int _id;
        public myClass(int id)
        {
            Id = id;
        }
        public int Id
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
            }
        }
    }

    public void BuildList()
    {
        List<myClass> myClassList1 = new List<myClass>();
        myClassList1.Add(new myClass(8));
        myClassList1.Add(new myClass(4));
        myClassList1.Add(new myClass(10));
        myClassList1.Add(new myClass(1));   // This would become the first item when the list is sorted.
        myClassList1.Add(new myClass(30));

        List<myClass> myClassList2 = new List<myClass>();
        foreach (myClass obj in myClassList1)
        {
            myClassList2.Add(obj);
        }

        myClassList2.Sort((s1, s2) => s1.Id.CompareTo(s2.Id));  // Sort by Id.

        // Modify the first element in the second sorted list.
        myClass firstElementList2 = myClassList2[0];
        firstElementList2.Id++;
        int valueInList2 = firstElementList2.Id; // Get the id that is incremented

        // Find the same object in first list...
        myClass sameElementInList1 = myClassList1.Find(x => x.Id.Equals(valueInList2));
        int valueInList1 = sameElementInList1.Id;

        if (valueInList2== valueInList1)
        {
            MessageBox.Show("Cheers!");
        }
    }

To test:

[TestMethod]
        public void SKTestMethod()
        {
            Class1 c1 = new Class1();
            c1.BuildList();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM