user6703592 user6703592 - 2 months ago 12
C# Question

C# Copy the Class List

Here is my Class:

public class Information
{
public Tuple<string, string> pair { get; set; }
public double Signal { get; set; }
public double SigmaMove { get; set; }
public DateTime Date { get; set; }
}

Inforamtion A = new Information() {};



  1. I want to use
    A.Clone()
    but there is no such method?

  2. How to Copy a
    List<Information> A = B
    by value not by reference(Change of A did not influent B, previous solutions in the website do not work .... I tried)?

  3. When I add a Initializing Constructor in the Class
    Information


    public class Information
    {
    public Tuple<string, string> pair { get; set; }
    public double Signal { get; set; }
    public double SigmaMove { get; set; }
    public DateTime Date { get; set; }

    public Information(Information Tem)
    {
    pair = Tem.pair;
    Signal = Tem.Signal ;
    SigmaMove = Tem.SigmaMove;
    Date = Tem.Date;
    }
    }



Then
Inforamtion A = new Information(){};
this constructor no longer work, is it becasue of covered by the new Constructor? Then how to remain this constructor?

Answer
  1. An object can be cloned implementing IClonable interface

    public class Information : ICloneable
    {
       public Tuple<string, string> pair { get; set; }
       public double Signal { get; set; }
       public double SigmaMove { get; set; }
       public DateTime Date { get; set; }
    
       public Information(Information Tem)
       {
          pair = Tem.pair;
          Signal  = Tem.Signal ;
          SigmaMove = Tem.SigmaMove;
          Date = Tem.Date;
       }           
    
       #region ICloneable Members
       public Information Clone() { return new Information(this); }
       object ICloneable.Clone()
       {
          return Clone();
       }
       #endregion
    }
    
  2. You can copy a list by value. Follow any of the steps below If you want to know more about extension method follow this link

You can use extension method as following

    static class Extensions
    {
      public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
      {
         return listToClone.Select(item => (T)item.Clone()).ToList();
      }
    }

OR If you do not want to use IClonable interface

    var InformationList = new List<Information>(infoList);
  1. You can overload a constructor (as Kirlac mentioned)

    public class Information
    {
      public Tuple<string, string> pair { get; set; }
      public double Signal { get; set; }
      public double SigmaMove { get; set; }
      public DateTime Date { get; set; }
    
      public Information()
      {}
    
      public Information(Information Tem)
      {
        pair = Tem.pair;
        Signal  = Tem.Signal ;
        SigmaMove = Tem.SigmaMove;
        Date = Tem.Date;
      }
    }