1

I try to add new record to my list and change data of it, but it's change all record of array, here is my class and code:

The class:

 public class TransportDto
{
        public int type { get; set; }
        public string url { get; set; }
        public int Relationship { get; set; }
}

loading data to my list:

IQueryable<TransportDto> list = _entities.Database.SqlQuery<TransportDto>(filterExpression).AsQueryable();


List<TransportDto> lst = list.ToList();
TransportDto help =lst[1];// adding record like one of my result
lst.Add(help);

Now I try to change value of lst[lst.Count-1] but when I change it , lst[1] change too

lst[lst.Count-1].type=3;

on result both lst[lst.Count-1] and lst[1] changes to 3, but I just try to change one record of array

sarzin
  • 19
  • 4

1 Answers1

1

When you write TransportDto help =lst[1];, you are getting the object at the index of 1. When you add this object to the list, you are adding the same object to the list not a copy of it. Which means in the list, the indices of 1 and lst.Count-1 point to the same object. When you access the object as lst[lst.Count-1] you are accessing this object and .type=3 makes changes to the object the two indices are pointing to.

If you want a copy of the object in lst[1], consider cloning the object. This could make a copy of the object. You can refer here: How to Clone Objects

To simplify, in your case you can create a clone function like this:

public class TransportDto
{
    public int type { get; set; }
    public string url { get; set; }
    public int Relationship { get; set; }

    public TransportDto Clone(){
        return new TransportDto{
            type = type,
            url = url,
            Relationship = Relationship
        };
    }
}

This clone function creates a new object of TransportDto and passes the same values thus creating a copy. Now in your list you can do this:

TransportDto help =lst[1].Clone();

Now help stores a copy of lst[1].

Neville Nazerane
  • 6,622
  • 3
  • 46
  • 79