首页 / .NET / 正文

[.NET/C#].NET/C#程序开发中克隆/拷贝一个泛型集合List<T>的方法有哪些?

9831 发布于: 2018-02-09 读完约需7分钟

问题描述

在.NET/C#的程序开发中,当前有一个泛型的集合对象List<T>。当前希望克隆/拷贝这个泛型集合对象List<T>。泛型集合中的元素对象T是可以克隆的(clonable),但是集合对象List<T>没有直接可以克隆的方法list.Clone()
在.NET/C#程序开发中,有哪些方式可以实现以上泛型集合对象List<T>的克隆/拷贝操作呢?

 方案一

可以创建一个静态扩展方法,如:

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

方案二

使用MemoryStream来序列化并反序列化以实现深拷贝对象,如:

public static object DeepClone(object obj) 
{
  object objResult = null;
  using (MemoryStream  ms = new MemoryStream())
  {
    BinaryFormatter  bf =   new BinaryFormatter();
    bf.Serialize(ms, obj);

    ms.Position = 0;
    objResult = bf.Deserialize(ms);
  }
  return objResult;
}

方案三

使用泛型集合的GetRange()方法,如:

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

方案四

使用第三方组件,比如AutoMapper来作映射处理
定义映射关系:

Mapper.CreateMap<YourType, YourType>();

使用AutoMapperConvertAll()方法来转换映射:

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

方案五

使用Newtonsoft.Json序列化后反序列化,实现对象的克隆与拷贝,如:

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

方案六

创建一个可克隆的泛型类,如:

public class CloneableList<T> : List<T>, ICloneable where T : ICloneable
{
  public object Clone()
  {
    var clone = new List<T>();
    ForEach(item => clone.Add((T)item.Clone()));
    return clone;
  }
}

方案七

public List<TEntity> Clone<TEntity>(List<TEntity> o1List) where TEntity : class , new()
    {
        List<TEntity> retList = new List<TEntity>();
        try
        {
            Type sourceType = typeof(TEntity);
            foreach(var o1 in o1List)
            {
                TEntity o2 = new TEntity();
                foreach (PropertyInfo propInfo in (sourceType.GetProperties()))
                {
                    var val = propInfo.GetValue(o1, null);
                    propInfo.SetValue(o2, val);
                }
                retList.Add(o2);
            }
            return retList;
        }
        catch
        {
            return retList;
        }
    }

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [C#].NET/C#程序开发中复制一个数据流(Stream)的内容到另一个数据流的方法有哪些?

下一篇: [.NET/C#].NET/C#程序开发中如何删除字符串中非字母/数字/横线的其他字符?方法有哪些呢?

本文永久链接码友网 » [.NET/C#].NET/C#程序开发中克隆/拷贝一个泛型集合List<T>的方法有哪些?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册