c# List深度复制

摘要:
但如果是嵌套的List列表,遍历这种方法就麻烦了很多。

原文:https://www.cnblogs.com/MRRAOBX/articles/6979479.html

由于List之间的相等的话,等于是把List的地址给赋值过去了,赋值后的List变化,会改变原有的List,并没有起到备份原始数据的作用,对于没有嵌套的List,可以采用遍历重新赋值的方法去赋值(传递的是值类型,并非引用类型),若List内的数据是一个类的话,赋值的时候需要重新实例化才行。但如果是嵌套的List列表,遍历这种方法就麻烦了很多。

因此,常见的对List进行复制克隆的方法,有以下三种:

方法一:

1

2

List<string>t=newList<string>();//original

List<string>t2=newList<string>(t.ToArray());// copy of t

方法二(个人推荐):

1

2

3

4

5

6

ItisaonelinerusingLINQ.

List<string>list1=newList<string>();

List<string>list2=newList<string>();

// This will copy all the items from list 1 to list 2

list1.ForEach(i=>list2.Add(i));

方法三:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

usingSystem;

usingSystem.Linq;

usingSystem.Collections.Generic;

usingSystem.Diagnostics;

namespaceDelegates

{

classX

{

publicintId{get;set;}

publicstringName{get;set;}

}

classY

{

publicintId{get;set;}

publicstringName{get;set;}

}

classProgram

{

staticvoidMain(string[]args)

{

List<X>x=newList<X>();

for(inti=0;i<100;i++)

x.Add(newX{Id=i,Name=string.Format("x_{0}",i.ToString())});

// copy x to y

List<Y>y=newList<Y>(x.ConvertAll<Y>(e=>{returnnewY{Id=e.Id,Name=e.Name};}));

Debug.Assert(x.Count==y.Count);

}

}

}

免责声明:文章转载自《c# List深度复制》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇python re模块lvm逻辑卷的拉伸与缩小下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Log4net配置

一 AssemblyInfo.cs文件 [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] 二 创建log4net.config文件 <?xml version="1.0" encoding="utf-8" ?>&...

Java实现POI读取Excel文件,兼容后缀名xls和xlsx

1、引入所需的jar包:   maven管理项目的话直接添加以下坐标即可: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId>...

itextPDF使用笔记

最近在做报表打印,使用的是itextPDF,第一次用到它,简单做个笔记。主要涉及到字体设置,文字处理操作,表格及单元格设置,绘制一些图形 IText中有三个处理text的类com.lowagie.text.Chunk,com.lowagie.text.Phrase,com.lowagie.text.Paragraph。 官网的API:https://api...

JavaScript中unicode编码与String互转(三种方法)

1.引言 JS本身就支持unicode转string功能,一共有三种方式和String单个字符转unicode编码。 2.方法 //unicode转String 1. eval("'" + str + "'");//当str中有带分号'或者"时,会报错,此时改成eval('"' + str + '"')即可 2. (new Function("retu...

Python开发WebService--使用soaplib库

Python开发WebService--使用soaplib库   使用soaplib开发基于Python语言的WebService主要有以下四个步骤:一、准备环境    S1:下载插件Python、soaplib、Twisted、lxml(soaplib依赖于lxml这个库)    S2:使用easy_install快速安装,如进入Python安装目录下(...

WPF多语言化的实现

  Metro插件系统系列就暂时停一下,这次我们讨论一下WPF的资源本地化实现,主要用到的:CultureInfo,ResourceManger,MarkupExtension,RESX文件,这些都是.NET框架提供的。 项目结构: 运行结果: 可在程序运行时,实时切换语言 CultureInfo   CultureInfo类表示有关特定区域性的信息...