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

后端 未结 7 2066
死守一世寂寞
死守一世寂寞 2021-01-03 22:06

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

相关标签:
7条回答
  • 2021-01-03 22:50
    List<MyType> copy = new List<MyType>(original);
    
    0 讨论(0)
  • 2021-01-03 22:50

    Have you tried Cloning (Clone()) each item and adding the clone to a new collection?

    0 讨论(0)
  • 2021-01-03 22:52

    I want to retrieve the list by value to be able to remove items before displaying them,

    var newlist = oldList.Where(<specify condition here>).ToList();
    
    0 讨论(0)
  • 2021-01-03 22:56

    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#?

    0 讨论(0)
  • 2021-01-03 23:03

    If you are using .NET 3.5, the resulting array can have ToList() called on it.

    0 讨论(0)
  • 2021-01-03 23:03

    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);
    
    0 讨论(0)
提交回复
热议问题