Users Pricing

forum

Home Forums How to copy a generic list in c#? – MindStick

How to copy a generic list in c#?

Anupam Mishra 2307 11 Jan 2016
I have two generic lists and I want to copy the contents of the first one to the second and then modify either list without affecting the other one and google hasn't been of much help since none of the proposed answers worked in my case.
I eventually got it working but the way I did it doesn't seem right. 

I hope a seasoned programmer can take take a look at my code and point out the proper way to do it or suggest a better solution to this admittedly silly problem.
class Program
{
    static void Main(string[] args)
    {
        // Making it readonly doesn't even compile.
        List<Cat> firstList = new List<Cat>
        {
            new Cat {Name = "Indian", Breed = "Persian", Age = 15},
            new Cat {Name = "Spenish", Breed = "Shy", Age = 17}
        };
        // Doesn't work.
        List<Cat> secondList = new List<Cat>(firstList);
        // Doesn't work.
        List<Cat> secondList = firstList.ToList();
        // Doesn't work.
        List<Cat> secondList = new List<Cat>();
        secondList.AddRange(firstList);
        // Doesn't work.
        List<Cat> secondList = new List<Cat>();
        secondList = firstList.GetRange(0, firstList.Count);
        // Doesn't work.
        Cat[] secondList = new Cat[2];
        firstList.CopyTo(secondList);
        // Doesn't work.
        Cat[] secondList = new Cat[2];
        var thirdList = firstList.ToArray().Clone();
        secondList = (Cat[])thirdList;
        List<Cat> secondList = new List<Cat>();
        foreach (var cat in firstList)
        {
            secondList.Add(new Cat
             {
                 Name = cat.Name,
                 Breed = cat.Breed,
                 Age = cat.Age
             });
        }
        Console.WriteLine(firstList[1].Age);
        Console.WriteLine(secondList[1].Age);
        secondList[1].Age++;
        Console.WriteLine(firstList[1].Age);
        Console.WriteLine(secondList[1].Age);
    }
}
class Cat
{
    public string Name;
    public string Breed;
    public int Age;
}




1 Answers

Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md