如果更改了一个列表的数据,为什么另一个列表也会更改? [英] Why the other list also changes if I have changed the data of one list?

查看:60
本文介绍了如果更改了一个列表的数据,为什么另一个列表也会更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上一堂课

class MatchAddress
{
    public string Name { get; set; }
    public string Taluka { get; set; }
    public string District { get; set; }
    public string Pincode { get; set; }
    public float Rank { get; set; }
}

我已经使用此类创建了一个新列表,如下所述

I have create new list using this class as mentioned below

var dst = ds.Tables[0].AsEnumerable()
                      .Select(s => new MatchAddress 
                       { 
                           Name = s.Field<String>("officename").Trim().ToLower(), 
                           Pincode = Convert.ToString(s.Field<double>("pincode")).Trim(), 
                           Taluka = s.Field<String>("Taluk").Trim(),
                           District = s.Field<String>("Districtname").Trim(), 
                           Rank = 0f 
                       })
                      .ToList();

我还初始化了新列表List<MatchAddress> lm;

现在我将dst列表分配给lm,如下所示

Now I'm assign dst list to lm like below

lm = dst ;


foreach (MatchAddress ma in lm)
{                       
    if (ma.Name == "xyz")
    {                              
        ma.Pincode = null;
    }
}

此后,确保列表lm的属性Pincode设置为null,其中名称="XYZ".

after this sure the Property Pincode for the list lm set to null where name = "XYZ".

,因此,列表lm进行了更新,并将pincode字段设置为null.

and for that reason list lm are update and set pincode field null .

但是我的问题是,为什么该列表lm还会更新列表dst的结果.

lm列表还在列表dst中将pincode设置为空.

and lm list also set pincode null in the list dst.

,然后将dst列表的克隆复制到lm中,那么为什么列表lm也会更改列表dst ??

and we make the clone of the dst list into lm so why list lm change the also list dst ??

我知道要在此背后提供答案,而不是为什么会发生这种情况(如果您知道的话),请立即让我来.

I know to reason behind this not the answer why this happen if you know then please let me now.

我不想回答这个问题

推荐答案

列表是引用类型数据.但您可以根据需要进行克隆.这是该方法的简单扩展方法

List is a reference type data. but you can make clone if you want. here is the simple extension method for that

static class Extensions
    {
        public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
        {
            return listToClone.Select(item => (T)item.Clone()).ToList();
        }
    }

这篇关于如果更改了一个列表的数据,为什么另一个列表也会更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆