简体   繁体   中英

how to copy a list to a new list, or retrieve list by value in c#

I noticed in c# there is a method for Lists: CopyTo -> that copies to arrays, is there a nicer way to copy to a new list? problem is, I want to retrieve the list by value to be able to remove items before displaying them, i dont want the original list to be modified, that too doesnt seem to be easily attainable, any ideas?

List<MyType> copy = new List<MyType>(original);

我想按值检索列表,以便能够在显示之前删除项目,

var newlist = oldList.Where(<specify condition here>).ToList();

如果您使用的是 .NET 3.5,则生成的数组可以调用 ToList()。

只需创建一个新List并使用适当的构造函数:

IList<Obj> newList = new List<Obj>(oldList);

I think this will work. Passing a list to the constructor of a new list.

    List<string> list1 = new List<string>();
    List<string> list2 = new List<string>(list1);

您是否尝试过克隆 (Clone()) 每个项目并将克隆添加到新集合中?

It seems if you have a list of references, the list

List<Object> list2 = new List<Object>(list1);

does not work.

This should solve your problem:

How do I clone a generic list in C#?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM