如何在C#中克隆通用列表?

五迷三道 提交于 2020-02-26 15:02:14

我在C#中有一个通用的对象列表,并希望克隆列表。 列表中的项目是可复制的,但似乎没有选项可以执行list.Clone()

有一个简单的方法吗?


#1楼

使用AutoMapper(或您喜欢的任何映射库)进行克隆非常简单且易于维护。

定义您的映射:

Mapper.CreateMap<YourType, YourType>();

做魔术:

YourTypeList.ConvertAll(Mapper.Map<YourType, YourType>);

#2楼

您可以使用扩展方法:

namespace extension
{
    public class ext
    {
        public static List<double> clone(this List<double> t)
        {
            List<double> kop = new List<double>();
            int x;
            for (x = 0; x < t.Count; x++)
            {
                kop.Add(t[x]);
            }
            return kop;
        }
   };

}

您可以使用其值类型成员克隆所有对象,例如,考虑以下类:

public class matrix
{
    public List<List<double>> mat;
    public int rows,cols;
    public matrix clone()
    { 
        // create new object
        matrix copy = new matrix();
        // firstly I can directly copy rows and cols because they are value types
        copy.rows = this.rows;  
        copy.cols = this.cols;
        // but now I can no t directly copy mat because it is not value type so
        int x;
        // I assume I have clone method for List<double>
        for(x=0;x<this.mat.count;x++)
        {
            copy.mat.Add(this.mat[x].clone());
        }
        // then mat is cloned
        return copy; // and copy of original is returned 
    }
};

注意:如果您对副本(或克隆)进行任何更改,则不会影响原始对象。


#3楼

我为自己做了一些扩展,它转换了ICollection没有实现IClonable的项目

static class CollectionExtensions
{
    public static ICollection<T> Clone<T>(this ICollection<T> listToClone)
    {
        var array = new T[listToClone.Count];
        listToClone.CopyTo(array,0);
        return array.ToList();
    }
}

#4楼

如果您已在项目中引用了Newtonsoft.Json,并且您的对象可序列化,则可以始终使用:

List<T> newList = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(listToCopy))

可能不是最有效的方法,但除非你做1000次,否则你可能甚至没有注意到速度差异。


#5楼

对于浅表副本,您可以改为使用泛型List类的GetRange方法。

List<int> oldList = new List<int>( );
// Populate oldList...

List<int> newList = oldList.GetRange(0, oldList.Count);

引自: 仿制食谱

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