Are there any better cloning methods for a list?

So I needed a method for deep cloning. I wanted one map list to be equal to another map list, but then I also wanted to change one of the clones.

I made a way to copy the list as follows:

    public List<Card> Copy(List<Card> cards)
    {
        List<Card> clone = new List<Card>();
        foreach (var card in cards)
        {
            clone.Add(card);
        }
        return clone;
    }

and use it as follows:

        _cards = new List<Card>();
        _thrownCards = new List<Card>();

        _cards = Copy(_thrownCards);
        _thrownCards.Clear();

I don't test in C #, but for some reason my gut feelings tell me that my copy method can be simplified. Is there no other way so you can copy the list? I tried using MemberWiseClone , but it just created references to the same object, not cloning (maybe I misinterpreted the MemberWiseClone method).

Does anyone have a clue how easy it is to clone a list object?

+4
4

, Card , . :

List<Card> cloneList = cards.ToList();

"" Card:

public List<Card> Copy(List<Card> cards)
{
    List<Card> cloneList = new List<Card>();
    foreach (var card in cards)
    {
        Card clone = new Card();
        clone.Property1 = card.Property1;
        // ... other properties
        cloneList.Add(clone);
    }
    return cloneList;
}

factory, Card:

public class Card
{
    // ...

    public Card GetDeepCopy()
    {
        Card deepCopy = new Card(); 
        deepCopy.Property1 = this.Property1;
        // ...
        return deepCopy;
    }
}

, private (, , ). Copy :

cloneList.Add(card.GetDeepCopy()); 
+5

, - :

public List<Card> Copy(List<Card> cards)
{
    List<Card> clone = new List<Card>();
    foreach (var card in cards)
    {
        clone.Add(new Card 
        {
          property1 = card.property1;
          property2 = card.property2; // and so on
        });
    }
    return clone;
}

, property1 property2 refference, .

+1

-

List<Card> _cards = _thrownCards.ConvertAll(Card => new Card(<card parameters here>));
0

,

 public List<Card> Copy(List<Card> cards) {
   return cards.ToList();
 }

:

 public List<Card> Copy(List<Card> cards) {
   return cards
     .Select(card => new Card() {
        //TODO: put the right assignment here  
        Property1 = card.Property1,
        ...
        PropertyN = card.PropertyN,
     }) 
     .ToList();
 }
0

Source: https://habr.com/ru/post/1678419/


All Articles