# Copy một List

#### Vấn đề:

- <span style="white-space: pre-wrap;">Trong C# khi tạo một list mới bằng các </span>`<span class="editor-theme-code">List<T> list = new(otherList)</span>`<span style="white-space: pre-wrap;"> thì các phần tử của </span>`<span class="editor-theme-code">list</span>`<span style="white-space: pre-wrap;"> vẫn được tham chiếu đến các phần tử của </span>`<span class="editor-theme-code">otherList</span>`

#### Nguyên nhân:

- <span style="white-space: pre-wrap;">Trong C# khi sử dụng lệnh </span>`<span class="editor-theme-code">List<T> list = new(otherList)</span>`<span style="white-space: pre-wrap;"> chỉ tạo ra được một shallow copy (copy nông). Các phần tử vẫn được tham chiếu đến một vị trí.</span>

#### Giải pháp

- Tạo ra một deep copy (copy sâu)
    - Sử dụng vòng for duyệt và tạo mới từng phần tử sau đó thêm vào list mới.
    - Sử dụng Linq để tạo phần từ mới
        - `<span class="editor-theme-code">List<T> list = otherList.Select(e => new T()).ToList();</span>`
        - `<span class="editor-theme-code">List<T> list = otherList.ConvertAll(e => new T());</span>`