Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move items from a list to another list in C#?

Tags:

c#

list

linq

What is the preferable way for transferring some items (not all) from one list to another.

What I am doing is the following:

var selected = from item in items                where item.something > 10                select item;  otherList.AddRange(selected);  items.RemoveAll(item => selected.Contains(item)); 

In the interest of having the fastest/best code there is, is there a better way?

like image 861
Stécy Avatar asked Jun 22 '09 20:06

Stécy


People also ask

How to add one list to another list in c# using linq?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);

How do I move items from one list to another in python?

Method : Using pop() + insert() + index() This particular task can be performed using combination of above functions. In this we just use the property of pop function to return and remove element and insert it to the specific position of other list using index function.

How do I get the length of a list in C#?

Try this: Int32 length = yourList. Count; In C#, arrays have a Length property, anything implementing IList<T> (including List<T> ) will have a Count property.


1 Answers

I'd try @Mehrdad's answer, and maybe test it against this one too...

var selected = items.Where(item => item.Something > 10).ToList(); selected.ForEach(item => items.Remove(item)); otherList.AddRange(selected); 
like image 127
Scott Ivey Avatar answered Sep 19 '22 08:09

Scott Ivey