[英]How do I clone a generic list in C#?
我在 C# 中有一个对象的通用列表,并希望克隆该列表。 列表中的项目是可克隆的,但似乎没有执行list.Clone()
的选项。
有没有简单的方法解决这个问题?
如果您的元素是值类型,那么您可以这样做:
List<YourType> newList = new List<YourType>(oldList);
但是,如果它们是引用类型并且您想要深层复制(假设您的元素正确实现ICloneable
),则可以执行以下操作:
List<ICloneable> oldList = new List<ICloneable>();
List<ICloneable> newList = new List<ICloneable>(oldList.Count);
oldList.ForEach((item) =>
{
newList.Add((ICloneable)item.Clone());
});
显然,替换上述泛型中的ICloneable
并使用实现ICloneable
任何元素类型进行转换。
如果您的元素类型不支持ICloneable
但确实有一个复制构造函数,您可以这样做:
List<YourType> oldList = new List<YourType>();
List<YourType> newList = new List<YourType>(oldList.Count);
oldList.ForEach((item)=>
{
newList.Add(new YourType(item));
});
就个人而言,我会避免使用ICloneable
因为需要保证所有成员的深层副本。 相反,我建议拷贝构造函数或工厂方法一样YourType.CopyFrom(YourType itemToCopy)
返回的新实例YourType
。
这些选项中的任何一个都可以由方法(扩展或其他)包装。
您可以使用扩展方法。
static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}
对于浅拷贝,您可以改用泛型 List 类的 GetRange 方法。
List<int> oldList = new List<int>( );
// Populate oldList...
List<int> newList = oldList.GetRange(0, oldList.Count);
引自: 泛型食谱
public static object DeepClone(object obj)
{
object objResult = null;
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, obj);
ms.Position = 0;
objResult = bf.Deserialize(ms);
}
return objResult;
}
这是使用 C# 和 .NET 2.0 实现的一种方法。 您的对象需要是[Serializable()]
。 目标是丢失所有引用并构建新引用。
要克隆一个列表,只需调用 .ToList()。 这将创建一个浅拷贝。
Microsoft (R) Roslyn C# Compiler version 2.3.2.62116
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> var x = new List<int>() { 3, 4 };
> var y = x.ToList();
> x.Add(5)
> x
List<int>(3) { 3, 4, 5 }
> y
List<int>(2) { 3, 4 }
>
稍作修改后,您还可以克隆:
public static T DeepClone<T>(T obj)
{
T objResult;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
ms.Position = 0;
objResult = (T)bf.Deserialize(ms);
}
return objResult;
}
除非您需要对List<T>
的每个对象进行实际克隆,否则克隆List<T>
的最佳方法是创建一个以旧列表作为集合参数的新列表。
List<T> myList = ...;
List<T> cloneOfMyList = new List<T>(myList);
对myList
更改(例如插入或删除)不会影响cloneOfMyList
,反之亦然。
然而,两个列表包含的实际对象仍然相同。
如果您只关心值类型...
你知道类型:
List<int> newList = new List<int>(oldList);
如果您之前不知道类型,则需要一个辅助函数:
List<T> Clone<T>(IEnumerable<T> oldList)
{
return newList = new List<T>(oldList);
}
刚刚:
List<string> myNewList = Clone(myOldList);
使用 AutoMapper(或您喜欢的任何映射库)进行克隆非常简单且易于维护。
定义您的映射:
Mapper.CreateMap<YourType, YourType>();
施展魔法:
YourTypeList.ConvertAll(Mapper.Map<YourType, YourType>);
如果您已经在项目中引用了 Newtonsoft.Json 并且您的对象是可序列化的,则可以始终使用:
List<T> newList = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(listToCopy))
可能不是最有效的方法,但除非您执行 100 次或 1000 次,否则您甚至可能不会注意到速度差异。
无需将类标记为可序列化,在我们的测试中,使用 Newtonsoft JsonSerializer 甚至比使用 BinaryFormatter 更快。 具有可用于每个对象的扩展方法。
标准 .NET JavascriptSerializer 选项:
public static T DeepCopy<T>(this T value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(value);
return js.Deserialize<T>(json);
}
使用Newtonsoft JSON 的更快选项:
public static T DeepCopy<T>(this T value)
{
string json = JsonConvert.SerializeObject(value);
return JsonConvert.DeserializeObject<T>(json);
}
如果有人读过这个,我会很幸运……但是为了不在我的 Clone 方法中返回类型对象的列表,我创建了一个接口:
public interface IMyCloneable<T>
{
T Clone();
}
然后我指定了扩展名:
public static List<T> Clone<T>(this List<T> listToClone) where T : IMyCloneable<T>
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
这是我的 A/V 标记软件中接口的实现。 我想让我的 Clone() 方法返回一个 VidMark 列表(而 ICloneable 接口想让我的方法返回一个对象列表):
public class VidMark : IMyCloneable<VidMark>
{
public long Beg { get; set; }
public long End { get; set; }
public string Desc { get; set; }
public int Rank { get; set; } = 0;
public VidMark Clone()
{
return (VidMark)this.MemberwiseClone();
}
}
最后,在类中使用扩展:
private List<VidMark> _VidMarks;
private List<VidMark> _UndoVidMarks;
//Other methods instantiate and fill the lists
private void SetUndoVidMarks()
{
_UndoVidMarks = _VidMarks.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;
}
}
//try this
List<string> ListCopy= new List<string>(OldList);
//or try
List<T> ListCopy=OldList.ToList();
对于深层复制,ICloneable 是正确的解决方案,但这里有一个类似的方法,使用构造函数而不是 ICloneable 接口来处理 ICloneable。
public class Student
{
public Student(Student student)
{
FirstName = student.FirstName;
LastName = student.LastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
// wherever you have the list
List<Student> students;
// and then where you want to make a copy
List<Student> copy = students.Select(s => new Student(s)).ToList();
您将需要以下库来制作副本
using System.Linq
您也可以使用 for 循环代替 System.Linq,但 Linq 使其简洁明了。 同样,您可以按照其他答案的建议进行操作并制作扩展方法等,但这都不是必需的。
public static Object CloneType(Object objtype)
{
Object lstfinal = new Object();
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, objtype); memStream.Seek(0, SeekOrigin.Begin);
lstfinal = binaryFormatter.Deserialize(memStream);
}
return lstfinal;
}
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;
}
}
您可以使用扩展方法:
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
}
};
注意:如果您对复制(或克隆)进行任何更改,它不会影响原始对象。
如果您需要具有相同容量的克隆列表,您可以试试这个:
public static List<T> Clone<T>(this List<T> oldList)
{
var newList = new List<T>(oldList.Capacity);
newList.AddRange(oldList);
return newList;
}
在这种情况下,对于浅拷贝,使用强制转换可能会有所帮助:
IList CloneList(IList list)
{
IList result;
result = (IList)Activator.CreateInstance(list.GetType());
foreach (object item in list) result.Add(item);
return result;
}
适用于通用列表:
List<T> Clone<T>(List<T> argument) => (List<T>)CloneList(argument);
我为自己做了一些扩展,它转换了不实现 IClonable 的项目的 ICollection
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();
}
}
我使用 automapper 来复制一个对象。 我只是设置了一个映射,将一个对象映射到自身。 您可以按您喜欢的任何方式包装此操作。
您也可以简单地使用ToArray
将列表转换为数组,然后使用Array.Clone(...)
克隆数组。 根据您的需要,Array 类中包含的方法可以满足您的需要。
有一种简单的方法可以使用 JSON 序列化器和反序列化器在 C# 中克隆对象。
您可以创建一个扩展类:
using Newtonsoft.Json;
static class typeExtensions
{
[Extension()]
public static T jsonCloneObject<T>(T source)
{
string json = JsonConvert.SerializeObject(source);
return JsonConvert.DeserializeObject<T>(json);
}
}
克隆和对象:
obj clonedObj = originalObj.jsonCloneObject;
以下代码应该转移到一个列表中,更改最少。
基本上它的工作原理是在每个连续循环中插入一个更大范围的新随机数。 如果已经存在与它相同或更高的数字,则将这些随机数向上移动一个,以便它们转移到新的更大范围的随机索引中。
// Example Usage
int[] indexes = getRandomUniqueIndexArray(selectFrom.Length, toSet.Length);
for(int i = 0; i < toSet.Length; i++)
toSet[i] = selectFrom[indexes[i]];
private int[] getRandomUniqueIndexArray(int length, int count)
{
if(count > length || count < 1 || length < 1)
return new int[0];
int[] toReturn = new int[count];
if(count == length)
{
for(int i = 0; i < toReturn.Length; i++) toReturn[i] = i;
return toReturn;
}
Random r = new Random();
int startPos = count - 1;
for(int i = startPos; i >= 0; i--)
{
int index = r.Next(length - i);
for(int j = startPos; j > i; j--)
if(toReturn[j] >= index)
toReturn[j]++;
toReturn[i] = index;
}
return toReturn;
}
另一件事:你可以使用反射。 如果您正确缓存它,那么它将在 5.6 秒内克隆 1,000,000 个对象(遗憾的是,内部对象需要 16.4 秒)。
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class Person
{
...
Job JobDescription
...
}
[ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]
public class Job
{...
}
private static readonly Type stringType = typeof (string);
public static class CopyFactory
{
static readonly Dictionary<Type, PropertyInfo[]> ProperyList = new Dictionary<Type, PropertyInfo[]>();
private static readonly MethodInfo CreateCopyReflectionMethod;
static CopyFactory()
{
CreateCopyReflectionMethod = typeof(CopyFactory).GetMethod("CreateCopyReflection", BindingFlags.Static | BindingFlags.Public);
}
public static T CreateCopyReflection<T>(T source) where T : new()
{
var copyInstance = new T();
var sourceType = typeof(T);
PropertyInfo[] propList;
if (ProperyList.ContainsKey(sourceType))
propList = ProperyList[sourceType];
else
{
propList = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ProperyList.Add(sourceType, propList);
}
foreach (var prop in propList)
{
var value = prop.GetValue(source, null);
prop.SetValue(copyInstance,
value != null && prop.PropertyType.IsClass && prop.PropertyType != stringType ? CreateCopyReflectionMethod.MakeGenericMethod(prop.PropertyType).Invoke(null, new object[] { value }) : value, null);
}
return copyInstance;
}
我通过使用 Watcher 类以一种简单的方式对其进行了测量。
var person = new Person
{
...
};
for (var i = 0; i < 1000000; i++)
{
personList.Add(person);
}
var watcher = new Stopwatch();
watcher.Start();
var copylist = personList.Select(CopyFactory.CreateCopyReflection).ToList();
watcher.Stop();
var elapsed = watcher.Elapsed;
结果:使用内部对象 PersonInstance - 16.4,PersonInstance = null - 5.6
CopyFactory 只是我的测试类,我有十几个测试,包括表达式的使用。 您可以在扩展或其他任何形式中以另一种形式实现这一点。 不要忘记缓存。
我还没有测试序列化,但我怀疑有一百万个类的改进。 我会尝试一些快速的protobuf/newton。
PS:为了阅读简单,我这里只用了auto-property。 我可以使用 FieldInfo 进行更新,或者您应该自己轻松实现。
我最近使用开箱即用的 DeepClone 功能测试了Protocol Buffers序列化器。 它在一百万个简单对象上以 4.2 秒获胜,但是对于内部对象,它以 7.4 秒的结果获胜。
Serializer.DeepClone(personList);
总结:如果您无权访问这些类,那么这将有所帮助。 否则,它取决于对象的数量。 我认为您可以使用最多 10,000 个对象的反射(可能会少一点),但除此之外,Protocol Buffers 序列化程序的性能会更好。
对于深度克隆,我使用反射如下:
public List<T> CloneList<T>(IEnumerable<T> listToClone) {
Type listType = listToClone.GetType();
Type elementType = listType.GetGenericArguments()[0];
List<T> listCopy = new List<T>();
foreach (T item in listToClone) {
object itemCopy = Activator.CreateInstance(elementType);
foreach (PropertyInfo property in elementType.GetProperties()) {
elementType.GetProperty(property.Name).SetValue(itemCopy, property.GetValue(item));
}
listCopy.Add((T)itemCopy);
}
return listCopy;
}
您可以交替使用 List 或 IEnumerable。
我有一个问题,我认为是我组合列表的方法有问题,因为它曾经工作过,但再也没有了。
结果完全没有关系,花了我很长时间才解决,因为我走错了路。
如果您尝试组合列表并通过 bindingsource 推送它们,则上述所有方法都有效,但您需要使用 ObservableCollection 而不是列表。
试试这个:
var res = ConvertModel<sourceModel, responseModle>(model);
public static T2 ConvertModel<T1, T2>(T1 data) where T1 : class, new()
{
return DeserializeObject<T2>(SerializeObject(data));
}
public static string SerializeObject<T>(T objectData)
{
string defaultJson = JsonConvert.SerializeObject(objectData);
return defaultJson;
}
public static T DeserializeObject<T>(string json)
{
T obj = default(T);
obj = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
return obj;
}
如果我需要收藏的深层副本,我最喜欢这样的方法:
public static IEnumerable<T> DeepCopy<T>(this IEnumerable<T> collectionToDeepCopy)
{
var serializedCollection = JsonConvert.SerializeObject(collectionToDeepCopy);
return JsonConvert.DeserializeObject<IEnumerable<T>>(serializedCollection);
}
您可以使用List<T>.ConvertAll(Converter<T, T>)
方法创建一个包含原始列表所有元素的新列表,并使用返回输入值的转换 function。
List<int> originalList = new List<int> { 1, 2, 3, 4, 5 };
List<int> clonedList = new List<int>(originalList.ConvertAll(x => x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.