List is changed when I update another list with same data type

我的梦境 提交于 2021-02-08 07:46:34

问题


My code looks like this.

public class Category
{
    public string CatId { get; set; }
    public string CatName { get; set; }
    public string SpecId { get; set; }
    public string SpecName { get; set; }
}

List<Category> LstCategory = new List<Category>();
List<Category> LstCatWithSpec = new List<Category>();

Now, I want to add category first in LstCatWithSpec. I copy this list in LstCategory and then add specialties in LstCatWithSpec. Now, when I update list with specialties, the list in which I copied only categories is also changed. It is also filled with specialties. It should not change right ?

How is this possible when I have two different objects and I give specific object name when I am adding items to it ?

As I am working on xamarin.forms, I have tagged xamarin.forms because I don't know if it exists in c# or not.

EDIT -

I tried to add list using foreach loop.

foreach( var item in LstCatWithSpec)
{
    LstCategory.Add(item); 
}

And I tried this also.

LstCategory = new List<Category>(LstCatWithSpec);

来源:https://stackoverflow.com/questions/40573715/list-is-changed-when-i-update-another-list-with-same-data-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!