Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 481
ratty Avatar asked Dec 23 '09 11:12

ratty


People also ask

Does ForEach work with lists?

Using the CodeThe ForEach method of the List<T> (not IList<T> ) executes an operation for every object which is stored in the list. Normally it contains code to either read or modify every object which is in the list or to do something with list itself for every object.

Can you ForEach a list?

forEach statement is a C# generic statement which you can use to iterate over elements of a List. Also, there is a ForEach() method that a List class implements in C#.

How to copy list entries from Lista to ListB?

If you as wanting to copy some specific entries from ListA into ListB you could use LINQ to retrieve the entries from ListA Regarding your statement about schema "where the schema of two lists are different".

How do you access a list in a for loop?

A list can be accessed by an index, a for/foreach loop, and using LINQ queries. Indexes of a list start from zero. Pass an index in the square brackets to access individual list items, same as array. Use a foreach or for loop to iterate a List<T> collection.

How to iterate a list<T> with different index?

Indexes of a list start from zero. Pass an index in the square brackets to access individual list items, same as array. Use a foreach or for loop to iterate a List<T> collection.

How to iterate a list<T> collection in Java?

Pass an index in the square brackets to access individual list items, same as array. Use a foreach or for loop to iterate a List<T> collection.


1 Answers

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.

like image 53
2 revs Avatar answered Oct 08 '22 11:10

2 revs