【转载】 C#中使用CopyTo方法将List集合元素拷贝到数组Array中

在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。

 

posted @ 2019-06-15 09:29  江湖逍遥  阅读(11414)  评论(0编辑  收藏  举报