forum

Home / DeveloperSection / Forums / How to copy a generic list in c#?

How to copy a generic list in c#?

Anupam Mishra175511-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.
classProgram
{
    staticvoid Main(string[] args)
    {
        // Making it readonly doesn't even compile.
        List<Cat> firstList = newList<Cat>
        {
            newCat {Name = "Indian", Breed = "Persian", Age = 15},
            newCat {Name = "Spenish", Breed = "Shy", Age = 17}
        };
        // Doesn't work.
        List<Cat> secondList = newList<Cat>(firstList);
        // Doesn't work.
        List<Cat> secondList = firstList.ToList();
        // Doesn't work.
        List<Cat> secondList = newList<Cat>();
        secondList.AddRange(firstList);
        // Doesn't work.
        List<Cat> secondList = newList<Cat>();
        secondList = firstList.GetRange(0, firstList.Count);
        // Doesn't work.
        Cat[] secondList = newCat[2];
        firstList.CopyTo(secondList);
        // Doesn't work.
        Cat[] secondList = newCat[2];
        var thirdList = firstList.ToArray().Clone();
        secondList = (Cat[])thirdList;
       List<Cat> secondList = newList<Cat>();
        foreach (var cat in firstList)
        {
            secondList.Add(newCat
             {
                 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);
    }
}
classCat
{
    publicstring Name;
    publicstring Breed;
    publicint Age;
}




Updated on 12-Jan-2016

Can you answer this question?


Answer

1 Answers

Liked By