Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add elements from one list to another C#

Tags:

What is the simplest way to add elements of one list to another?

For example, I have two lists:

List A which contains x items List B which contains y items.

I want to add elements of B to A so that A now contains X+Y items. I know this can done using a loop but is there a built in method for this? Or any other technique?

like image 686
R.S.K Avatar asked Nov 20 '12 05:11

R.S.K


People also ask

How to Add a list into Another list in C#?

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

How to Add method in C#?

C# | Insert() Method Indexvalue: It is the index position of current string where the new value will be inserted. The type of this parameter is System. Int32. value: The String value to be inserted the type of this parameter is System.

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.


2 Answers

Your question describes the List.AddRange method, which copies all the elements of its argument into the list object on which it is called.

As an example, the snippet

List<int> listA = Enumerable.Range(0, 10).ToList(); List<int> listB = Enumerable.Range(11, 10).ToList(); Console.WriteLine("Old listA: [{0}]", string.Join(", ", listA)); Console.WriteLine("Old listB: [{0}]", string.Join(", ", listB)); listA.AddRange(listB); Console.WriteLine("New listA: [{0}]", string.Join(", ", listA)); 

prints

Old listA: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Old listB: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] New listA: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] 

showing that all the elements of listB were added to listA in the AddRange call.

like image 132
Adam Mihalcin Avatar answered Oct 13 '22 23:10

Adam Mihalcin


To join two lists, you can do

listA.AddRange(listB); // listA will contain x+y items 

or

// listC contains x+y items, listA and listB are unchanged. var listC = listA.Concat(listB);  

You could use the latter to reassign listA instead:

listA = listA.Concat(listB).ToList(); 

but there isn't any particular advantage to that over AddRange if you're okay with modifying one of the original lists in the first place.

like image 28
Adam Lear Avatar answered Oct 13 '22 22:10

Adam Lear