标签:Index C# List testList TestModel CopyTo 集合 拷贝到
在C#的List集合操作中,有时候需要将List元素对象拷贝存放到对应的数组Array中,此时就可以使用到List集合的CopyTo方法来实现,CopyTo方法是List集合的扩展方法,共有3个重载方法签名,分别为void CopyTo(T[] array)、void CopyTo(T[] array, int arrayIndex)、void CopyTo(int index, T[] array, int arrayIndex, int count)等三种形式,此文重点介绍CopyTo的第一种方法签名形式void CopyTo(T[] array)。
首先定义个用于测试的类TestModel,具体的类定义如下:
public class TestModel { public int Index { set; get; } public string Name { set; get; } }
然后定义一个List<TestModel>集合,并往里面写入3条TestModel数据,具体实现如下:
List<TestModel> testList = new List<ConsoleApplication1.TestModel>(); testList.Add(new TestModel() { Index=1, Name="Index1" }); testList.Add(new TestModel() { Index = 2, Name = "Index2" }); testList.Add(new TestModel() { Index = 3, Name = "Index3" });
我们需要达到的目的是,将testList集合的元素对象拷贝到数组Array中,此时可使用下列语句实现:
TestModel[] copyArray = new TestModel[testList.Count]; testList.CopyTo(copyArray);
注意:上述程序语句中的CopyTo方法为浅层次拷贝,当修改copyArray数组的时候,也会联动修改List集合对象testList。例如赋值copyArray[0].Index = 10后,List集合对象testList的第一个元素testList[0]对象的Index属性也被修改为10。
备注:原文转载自博主个人站IT技术小趣屋,原文链接 C#中使用CopyTo方法将List集合元素拷贝到数组Array中_IT技术小趣屋。
标签:Index,C#,List,testList,TestModel,CopyTo,集合,拷贝到 来源: https://www.cnblogs.com/xu-yi/p/11026480.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。