当前位置: 移动技术网 > IT编程>开发语言>.net > 【转载】 C#中使用CopyTo方法将List集合元素拷贝到数组Array中

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

2019年06月16日  | 移动技术网IT编程  | 我要评论

在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技术小趣屋

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网