我在c#中有一个对象的通用列表,并希望克隆列表。列表中的项是可克隆的,但似乎没有做list. clone()的选项。

有什么简单的办法吗?


当前回答

使用AutoMapper(或任何您喜欢的映射库)来克隆是简单的,而且易于维护。

定义映射:

Mapper.CreateMap<YourType, YourType>();

施展魔法吧:

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

其他回答

如果你已经参考了Newtonsoft。Json在你的项目和你的对象是可序列化的,你可以总是使用:

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

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

您可以使用扩展方法。

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

如果我需要深度拷贝集合,我有最喜欢的方法如下:

public static IEnumerable<T> DeepCopy<T>(this IEnumerable<T> collectionToDeepCopy)
{
    var serializedCollection = JsonConvert.SerializeObject(collectionToDeepCopy);
    return JsonConvert.DeserializeObject<IEnumerable<T>>(serializedCollection);
}

如果你只关心值类型……

你知道这种类型:

List<int> newList = new List<int>(oldList);

如果你之前不知道类型,你需要一个helper函数:

List<T> Clone<T>(IEnumerable<T> oldList)
{
    return newList = new List<T>(oldList);
}

公正:

List<string> myNewList = Clone(myOldList);

如果你需要一个具有相同容量的克隆列表,你可以尝试这样做:

public static List<T> Clone<T>(this List<T> oldList)
{
    var newList = new List<T>(oldList.Capacity);
    newList.AddRange(oldList);
    return newList;
}