Difference Between Add vs AddRange & Insert vs InsertRange in ArrayList C#

12 April 2023 | Viewed 3899 times

Add() vs AddRange()


List.Add()

Adds an element to the end of the List<T>.

C# Code
//syntax
void List<T>.Add(T item)

//ex:-
List<string> list = new List<string>{ "ADF", "App Services" };
list.Add("Function App");

//output
//{ "ADF", "App Services", "Function App" }


List.AddRange()

Adds the elements of the specified collection to the end of the List<T>.

C# Code
//syntax
void List<T>.AddRange(IEnumerable<T> collection)

//ex:-
List<string> list = new List<string>{ "Azure", "iCloud" };

List<string> collection =new List<string>{ "AWS", "GCP" }
list.AddRange(collection)

//output
//{ "Azure", "iCloud", "AWS", "GCP" }


Insert() vs InsertRange()


List.Insert()

Inserts an element into the List<T> at the specified index.

C# Code
//syntax
void List<T>.Insert(int index, T item)

//ex:-
List<string> list = new List<string>{ "Azure Databricks", "Data Factories" };
list.Insert(0, "Event Hubs");

//output
//{ "Event Hubs", "Azure Databricks", "Data Factories" }

In the above example "Event Hubs" will be inserted at position 0 in the list.

List.InsertRange()

Inserts the elements of the collection into the the List<T> at the specified index.

C# Code
//syntax
void List<T>.InsertRange(int index, IEnumerable<T> collection)

//ex:-
List<string> list = new List<string>{ "Logic Apps", "Service Bus" };

List<string> collection =new List<string>{ "Data Catalog", "Event Grids" }
list.InsertRange(1, collection)

//output
//{ "Logic Apps", "Data Catalog", "Event Grids", "Service Bus" }

In the above example, collection of items will be inserted to the list at position 1.

PreviousNext