How do I copy items from list to list without foreach?

475,847

Solution 1

You could try this:

List<Int32> copy = new List<Int32>(original);

or if you're using C# 3 and .NET 3.5, with Linq, you can do this:

List<Int32> copy = original.ToList();

I see that this answer is still getting upvotes. Well, here's a secret for ya: the above answer is still using a foreach. Please don't upvote this any further.

Solution 2

To add the contents of one list to another list which already exists, you can use:

targetList.AddRange(sourceList);

If you're just wanting to create a new copy of the list, see the top answer.

Solution 3

For a list of elements

List<string> lstTest = new List<string>();

lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");

If you want to copy all the elements

List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);

If you want to copy the first 3 elements

List<string> lstNew = lstTest.GetRange(0, 3);

Solution 4

And this is if copying a single property to another list is needed:

targetList.AddRange(sourceList.Select(i => i.NeededProperty));

Solution 5

This method will create a copy of your list but your type should be serializable.

Use:

List<Student> lstStudent = db.Students.Where(s => s.DOB < DateTime.Now).ToList().CopyList(); 

Method:

public static List<T> CopyList<T>(this List<T> lst)
    {
        List<T> lstCopy = new List<T>();
        foreach (var item in lst)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, item);
                stream.Position = 0;
                lstCopy.Add((T)formatter.Deserialize(stream));
            }
        }
        return lstCopy;
    }
Share:
475,847
ratty
Author by

ratty

I Am Software developer from india.I am working as software developer in C#.net for past 1 Year .Contact me thorugh [email protected].

Updated on July 08, 2022

Comments

  • ratty
    ratty almost 2 years

    How do I transfer the items contained in one List to another in C# without using foreach?