Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T>().Add problem C#

Tags:

c#

list

I made a List to hold object in it, and then i'll read it. But even if i give an index to List, i always get the same object results. Here is the code:

            List<TempIds> treeDIds = new List<TempIds>();
            TempIds tempIds = new TempIds();


            foreach (ItemGroupTreeD treeD in itemTreeDColl)
            {

                //Idleri listeye alıyoruz daha sonra karşılaştırma yapmak için
                tempIds.TreeDId = treeD.Id;
                tempIds.TreeParentId = treeD.TreeParentId;
                treeDIds.Insert(treeDIds.Count, tempIds);
                //----

                //Eğer ilk gelen detay id ile methoda gelen id bir ise collectiona ekliyoruz.
                if (tempIds.TreeDId == groupTreeDId)
                {
                    treeDTempColl.Add(treeD);
                }
                else
                {
                    //Burada karşılaştırma yapıyoruz.
                    for (int i = 0; i < treeDIds.Count; i++)
                    {
                        if (tempIds.TreeParentId == treeDIds[i].TreeDId)
                        {
                            treeDTempColl.Add(treeD);
                            break;
                        }
                    }
                }

            }

For example:

For the first loop TreeDId = 3 and TreeParentId = 1 then i insert them index 0. second loop TreeDId = 2, TreeParentId = 1, then insert them index 1. When loop into the List, i always get TreeDId = 2 and TreeParentId = 1, because the last loop is the second loop. What else i can do?

Thank you.

like image 356
mehmetserif Avatar asked Dec 21 '22 22:12

mehmetserif


1 Answers

There is only 1 tempIds object. the item in the list is the same one, and has the last item in it. move the TempIds tempIds = new TempIds(); into the loop

        foreach (ItemGroupTreeD treeD in itemTreeDColl)
        {
          TempIds tempIds = new TempIds();

Remember that a list doesn't contain copies of the data you add. It contains a reference to the object you've added. Doing it this way create a new object for you to insert every time.

like image 176
Preet Sangha Avatar answered Dec 24 '22 13:12

Preet Sangha