Как скопировать list в list c

от admin

Как скопировать элементы из списка в список без использования foreach?

Как передать элементы, содержащиеся в одном List , в другой в C # без использования foreach ?

10 ответов

Вы можете попробовать это:

Или если вы используете C # 3 и .NET 3.5, с Linq, вы можете сделать это:

Я вижу, что этот ответ все еще получает положительные отзывы. Что ж, вот вам секрет: в приведенном выше ответе все еще используется foreach . Пожалуйста, не голосуйте дальше.

Добавляя к верхним ответам, если вам нужны копии «объектов в списке», вы можете использовать Select и делать копии. (В то время как другие ответы составляют «копию списка», этот ответ составляет «список копий»).

Предположим, что ваш элемент имеет метод Copy :

Или что вы можете создать новый объект из предыдущего с помощью конструктора:

Результатом Select является IEnumerable<MyObject> , который вы также можете передать AddRange , например, если ваша цель — добавить в существующий список.

Как добавить List в List?

Добрый вечер.
Помогите с решением задачи. Возможно она проста, но я пока что не додумался:)
Имеется парочка вот таких моделей.

Далее создаю простой класс менеджер, который бы заполнял мне список пользователей.

Проблема следующая. Могу ли я создать список в списке? В чем стоит задача. Есть абстрактный список пользователей.
У каждого пользователя есть определенное количество данных о аккаунтах. Аккаунтов может быть много а пользователь один.
И вообще возможно ли подобное? Что бы у элемента списка мог быть свой еще список.

  • Вопрос задан более трёх лет назад
  • 1554 просмотра

Простой 2 комментария

  • Facebook
  • Вконтакте
  • Twitter

Вопрос не совсем понятен. В вашей модели и так у пользователя определен список аккаунтов:

How To Clone a List in C#

We can easily clone or copy a list to another list or array in C#. In this blog, we will use 3 different methods to clone or copy a list. It is very simple to do if you see our examples.

  • Using List Constructor
  • Using Enumerable.ToList Method (System.Linq)
  • Using List<T>.CopyTo Method

Using List Constructor

First, we use the List constructor to inject/pass the source list, this will create a copy of the list which you passed through the constructor. The below code snippet shows how to clone the list using the List constructor.

Читать:
Как ввести значение в javascript

Using Enumerable.ToList Method (System.Linq)

We use ToList() method to copy or clone the list to another list as shown in the below example. The ToList() returns the new List<T> that containing the original list.

Using List<T>.CopyTo Method

In this method, we use CopyTo() method to copy the entire List<T> to a one-dimensional array, starting at the beginning of the target array. as shown below.

Как скопировать list в list c

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Visual studio home link

  • ProfileText
  • Sign in

Answered by:

Question

Am new to c#.Can any one tell me how to copy one list to another and changes happens in one list should reflect in another .

  • Edited by Jayashree.R.D Tuesday, January 15, 2013 8:19 AM

Answers

You could try this:

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

  • Proposed as answer by rama kotaru Tuesday, January 15, 2013 9:11 AM
  • Marked as answer by Jayashree.R.D Tuesday, January 15, 2013 9:41 AM

Could you please tell us more about the problem ?

Do you mean a lists of strings or objects like this :

Or do you mean a listbox on a form ? or something else.

Do you need to copy all items at once ? Do you need to make a selection of items ? Do you need to keep the lists in sync ?

If you do mean a list of object or strings you can do all objects in a list constructor or you can loop through the items and select the ones you need or you can use Linq to select items :

Hope this helps,

Here to learn and share. Please tell if an answer was helpful or not at all. This adds value to the answers and enables me to learn more.

Похожие статьи