How do I clone a generic list in C#?

前端 未结 26 2503
失恋的感觉
失恋的感觉 2020-11-22 01:27

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()

相关标签:
26条回答
  • 2020-11-22 02:16
     //try this
     List<string> ListCopy= new List<string>(OldList);
     //or try
     List<T> ListCopy=OldList.ToList();
    
    0 讨论(0)
  • 2020-11-22 02:22

    I've made for my own some extension which converts ICollection of items that not implement IClonable

    static class CollectionExtensions
    {
        public static ICollection<T> Clone<T>(this ICollection<T> listToClone)
        {
            var array = new T[listToClone.Count];
            listToClone.CopyTo(array,0);
            return array.ToList();
        }
    }
    
    0 讨论(0)
提交回复
热议问题