Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Add and AddRange in arrayList c#

Tags:

c#

Can anyone tell when to use Add() and AddRange() of ArrayList?

like image 658
user3483639 Avatar asked Jul 14 '15 06:07

user3483639


3 Answers

Difference Between Add and AddRange

Add---------It is used to add the item into the list one by one.

AddRange-----------It is used to add the bulk of list item into the another list.

List<string>list1=new List<string>();//using Add
List<string>list2=new List<string>();//using AddRange
list1.Add("Malathi");
list1.Add("Sandhiya");
list1.Add("Ramya");
list1.Add("Mithra");
list1.Add("Dharshini");

list2.AddRange(list1);

output:

//The output of list1 contains

Malathi, Sandhiya, Ramya, Mithra, Dharshini

//The output of list2 Contains

Malathi, Sandhiya, Ramya, Mithra, Dharshini

like image 189
Maghalakshmi Saravana Avatar answered Sep 28 '22 04:09

Maghalakshmi Saravana


If you want to add a large number of values at one time, use AddRange. If you are only adding a single value or adding values infrequently, use Add

like image 28
Takepatience Avatar answered Sep 28 '22 03:09

Takepatience


C# List class represents a collection of a type in C#. List.Add(), List.AddRange(), List.Insert(), and List.InsertRange() methods are used to add and insert items to a List.

AddRange - AddRange adds an entire collection of elements. It can replace tedious foreach-loops that repeatedly call Add on List.

public virtual void AddRange (System.Collections.ICollection c);

Add - Add method adds an object to the end of the List.

public virtual int Add (object value);

Example: Now set an array of elements to be added to the list.

// array of 4 elements
int[] arr = new int[4];
arr[0] = 500;
arr[1] = 600;
arr[2] = 700;
arr[3] = 800;

Use the AddRange() method add the entire collection of elements in the list −

List<int> list = new List<int>();
list.AddRange(arr);

But if you want to use List.Add() method,

List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);

For details, you can check Insert an Item into a C# List

like image 36
Sakib Ahammed Avatar answered Sep 28 '22 02:09

Sakib Ahammed