379

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

1

10 Answers 10

667

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.

7
  • 22
    If the items are of type MyClass instead of Integer, does it copy the items too, or just reference them? Commented Jun 6, 2014 at 14:14
  • 9
    Not working with Non-primitive types. List<StudentClass> copy = new List<StudentClass>(lstStudentClass);
    – garish
    Commented Apr 3, 2015 at 10:59
  • 4
    It works with all types, as long as lstStudentClass is an IEnumerable<StudentClass>, it will work. If you experience otherwise you need to provide more information. Commented Apr 3, 2015 at 11:05
  • 1
    what is the meaning of (original); at the end Commented Sep 13, 2015 at 14:40
  • 3
    @PedroMoreira For complex object you can do: origninal.Select(o => new Complex(o)).ToList() to get a list of new objects, not copied references Commented Jun 20, 2017 at 16:25
211

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.

4
  • 6
    @mrmillsy: Well they do different things. My answer is focused on "I already have a list, and I want to copy things to it"
    – Jon Skeet
    Commented Mar 1, 2013 at 12:44
  • True. My question would probably be better suited to a new question anyway. Thanks for the reply though.
    – mrmillsy
    Commented Mar 1, 2013 at 12:47
  • 3
    If you wanted to replace the contents of an existing list completely, you would call targetList.Clear() first.
    – Ibraheem
    Commented Jul 20, 2013 at 15:16
  • This is the correct answer as copying implies adding, not replacing. The OP asked for copying ITEMS not the entire collection.
    – John Stock
    Commented Jan 16, 2021 at 3:22
45

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);
1
  • 1
    This is the correct answer. AddRange does not specify it in the docs, that it copies or just adds objects by reference, but if you search the implementation, it uses Array.Copy (static) to copy the data. Commented Apr 26, 2021 at 19:43
7

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

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

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;
    }
1
  • Does the serialization create a significant performance penalty?
    – Dan Def
    Commented Nov 2, 2016 at 13:43
4

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();
2

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.

1
public static List<string> GetClone(this List<string> source)
{
    return source.Select(item => (string)item.Clone()).ToList();
}
1
  • 1
    Code only answer tend to be considered low quality. Can you add an explanation as to how your answer solves the issue, and how this differs from existing answers.
    – Dijkgraaf
    Commented Mar 1, 2021 at 3:05
-1

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 );
}
2
  • 3
    This is not even an answer. Commented Aug 30, 2017 at 14:20
  • mmm...ok well some of the suggestions above simply don't work in Vis 17 I have cleaned up the best answer provided...and hey presto...it works :) Commented Aug 30, 2017 at 14:31
-9

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

List<int> i=original.Take(original.count).ToList();
2
  • 25
    Why would you do that? Why not ToList() directly?
    – nawfal
    Commented Sep 23, 2013 at 19:10
  • Well I think, If I wanted to copy only the first 10 elements from one list to another, this would make sense. List<int> i=original.Take(10).ToList(); Commented Jul 3, 2022 at 10:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.