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

C#OopListForeachCopy

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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 - C#

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

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

Solution 5 - C#

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;
    }

Solution 6 - C#

Easy to map different set of list by linq without for loop

var List1= new List<Entities1>();

var List2= new List<Entities2>();

var List2 = List1.Select(p => new Entities2
        {
            EntityCode = p.EntityCode,
            EntityId = p.EntityId,
            EntityName = p.EntityName
        }).ToList();

Solution 7 - C#

OK this is working well From the suggestions above GetRange( ) does not work for me with a list as an argument...so sweetening things up a bit from posts above: ( thanks everyone :)

/*  Where __strBuf is a string list used as a dumping ground for data  */
public List < string > pullStrLst( )
{
    List < string > lst;

    lst = __strBuf.GetRange( 0, __strBuf.Count );     
        
    __strBuf.Clear( );

    return( lst );
}

Solution 8 - C#

Adding to the top answers, if you want copies of "the objects in the list", then you can use Select and make the copies. (While the other answers make "a copy of a list", this answer makes "a list of copies").

Suppose your item has a Copy method:

List<MyObject> newList = oldList.Select(item => item.Copy()).ToList();

Or that you can create a new object from the previous one with a constructor:

List<MyObject> newList = oldList.Select(item => new MyObject(item)).ToList();   

The result of Select is an IEnumerable<MyObject> that you can also pass to AddRange for instance, if your goal is to add to an existing list.

Solution 9 - C#

public static List<string> GetClone(this List<string> source)
{
    return source.Select(item => (string)item.Clone()).ToList();
}

Solution 10 - C#

Here another method but it is little worse compare to other.

List<int> i=original.Take(original.count).ToList();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrattyView Question on Stackoverflow
Solution 1 - C#Lasse V. KarlsenView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#ParasView Answer on Stackoverflow
Solution 4 - C#usefulBeeView Answer on Stackoverflow
Solution 5 - C#garishView Answer on Stackoverflow
Solution 6 - C#RajeevView Answer on Stackoverflow
Solution 7 - C#Jim StevensView Answer on Stackoverflow
Solution 8 - C#Daniel MöllerView Answer on Stackoverflow
Solution 9 - C#Black DreamView Answer on Stackoverflow
Solution 10 - C#rattyView Answer on Stackoverflow