0% found this document useful (0 votes)
23 views

List In C#-1

The C# List Tutorial provides comprehensive guidance on using the List<T> class in C#, covering its creation, manipulation, and various methods such as adding, removing, sorting, and searching items. It explains key properties like Capacity and Count, and demonstrates practical examples for each operation. The tutorial also includes advanced topics like merging lists and converting lists to arrays.

Uploaded by

jacksonn.clarkk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

List In C#-1

The C# List Tutorial provides comprehensive guidance on using the List<T> class in C#, covering its creation, manipulation, and various methods such as adding, removing, sorting, and searching items. It explains key properties like Capacity and Count, and demonstrates practical examples for each operation. The tutorial also includes advanced topics like merging lists and converting lists to arrays.

Uploaded by

jacksonn.clarkk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

C# List Tutorial - Everything You Need To Learn About List In C#

C# Corner Login

C# List Tutorial - Everything You Need To Learn About


List In C#
Mahesh Chand Apr 02, 2023 1.4m 29 57

C# List class represents a collection of strongly typed objects that can be accessed by index. This tutorial
teaches how to work with lists in C# using the C# List class to add, find, sort, reverse, and search items in
a collection of objects using List class methods and properties.

What is C# List?
List<T> class in C# represents a strongly typed list of objects. The C# List provides functionality to create a
list of objects, add items to a list, and find, sort, and update items in the List. In this article, learn how to
create a list in C#, add items to a list, and find and remove items to a list.

Create a List in C#
C# List is a generic class and is defined in the System.Collections.Generic namespace. You must import
this namespace in your project to access the List <T>, class.

1 using System.Collections.Generic;

List<T> class constructor is used to create a List object of type T. It can either be empty or take an Integer
value as an argument that defines the initial size of the List, also known as capacity. If no integer is passed
in the constructor, the size of the List is dynamic and grows every time an item is added to the array. You
can also give an initial collection of elements when initializing an object.

The code snippet in Listing 1 creates a List of Int16 and a list of string types. The last part of the code
creates a List<T> object with an existing collection.

1 // List with default capacity


2 List<Int16> list = new List<Int16>();
3 // List with capacity = 5
4 List<string> authors = new List<string>(5);
5 string[] animals = { "Cow", "Camel", "Elephant" };
6 List<string> animalsList = new List<string>(animals);

Listing 1.

As you can see from Listing 1, the List <string> has only an initial capacity set to 5. However, when more

https://www.c-sharpcorner.com/article/c-sharp-list/[10/30/2024 12:34:31 PM]


C# List Tutorial - Everything You Need To Learn About List In C#

than five elements are added to the List, it automatically expands.

Add an item to a C# List


The Add method adds an element to a C# List. For example, the code snippet in Listing 2 creates two List
<T> objects and adds integer and string items.

1 // Dynamic ArrayList with no size limit


2 List<int> numberList = new List<int>();
3 numberList.Add(32);
4 numberList.Add(21);
5 numberList.Add(45);
6 numberList.Add(11);
7 numberList.Add(89);
8 // List of string
9 List<string> authors = new List<string>(5);
10 authors.Add("Mahesh Chand");
11 authors.Add("Chris Love");
12 authors.Add("Allen O'neill");
13 authors.Add("Naveen Sharma");
14 authors.Add("Monica Rathbun");
15 authors.Add("David McCarter");

Listing 2.

We can also add a collection to a List. The AddRange method is used to add a group to a List. For
example, the code snippet in Listing 3 adds an array of strings to a List.

1 // Collection of string
2 string[] animals = { "Cow", "Camel", "Elephant" };
3 // Create a List and add a collection
4 List<string> animalsList = new List<string>();
5 animalsList.AddRange(animals);
6 foreach (string a in animalsList)
7 Console.WriteLine(a);

Listing 3.

Loop through a C# List items


The C# List is a collection of items. We can use a foreach loop to loop through its items. The code snippet
in Listing 6 reads all list items and displays them on the console.

https://www.c-sharpcorner.com/article/c-sharp-list/[10/30/2024 12:34:31 PM]


C# List Tutorial - Everything You Need To Learn About List In C#

1 foreach (string a in authors)


2 Console.WriteLine(a);

Listing 4.

We can use the collection's index to retrieve an item in a C# List at a specific position. For example, the
following code snippet reads the 3rd item in the List.

1 Console.WriteLine(authors[2]);

C# List properties
List class properties include the following:

Capacity – Number of elements List<T> can contain. The default capacity of a List<T> is 0.
Count – Number of elements in List <T>.

The code snippet in Listing 5 gets the value of these properties.

1 ArrayList authorsArray = new ArrayList();


2 authorsArray.Add("Mahesh Chand");
3 authorsArray.Add("Praveen Kumar");
4 authorsArray.Add("Raj Kumar");
5 authorsArray.Add("Dinesh Beniwal");
6 authorsArray.Add("David McCarter");
7 Console.WriteLine("Count: " + authors.Count);
8 Console.WriteLine("Capacity: " + authors.Capacity);

Listing 5.

Insert an item at a position in a C# List


The Insert method of the List class inserts an object at a given position. The first parameter of the method
is the 0th-based index in the List.

The InsertRange method can insert a collection at the given position.

The code snippet in Listing six inserts a string at the 3rd position and an array at the 2nd position of the List
<T>.

1 authors.Insert(3, "Bill Author");


2 // Collection of new authors
3 string[] newAuthors = { "New Author1", "New Author2", "New Author3" };
4 // Insert array at position 2
5 authors.InsertRange(2, newAuthors);

https://www.c-sharpcorner.com/article/c-sharp-list/[10/30/2024 12:34:31 PM]


C# List Tutorial - Everything You Need To Learn About List In C#

Listing 6.

Remove an item from a C# List


The List class provides Remove methods that can be used to remove an item or a range of items.

The Remove method removes the first occurrence of the given item in the List. For example, the following
code snippet removes the first occurrence of 'New Author1'.

1 // Remove an item
2 authors.Remove("New Author1");

The RemoveAt method removes an item at the given position. For example, the following code snippet
removes the item at the 3rd position.

1 // Remove 3rd item


2 authors.RemoveAt(3);

The RemoveRange method removes a list of items from the starting index to the number of items. For
example, the following code snippet removes two items starting at the 3rd position.

1 // Remove a range
2 authors.RemoveRange(3, 2);

The Clear method removes all items from a List<T>. For example, the following code snippet removes all
items from a List.

1 // Remove all items


2 authors.Clear();

Clear all items from a C# List


The Clear method removes all items from a C# List. For example, the following code snippet removes all
items from a List.

1 // Remove all items


2 authors.Clear();

Check if an item exists in a C# List


The IndexOf method finds an item in a List. The IndexOf method returns -1 if no items are located in the
List.

https://www.c-sharpcorner.com/article/c-sharp-list/[10/30/2024 12:34:31 PM]


C# List Tutorial - Everything You Need To Learn About List In C#

The following code snippet finds a string and returns the matched position of the item.

1 int idx = authors.IndexOf("Naveen Sharma");


2 if (idx > 0)
3 Console.WriteLine($"Item index in List is: {idx}");
4 else
5 Console.WriteLine("Item not found");

We can also specify the position in a List from which the IndexOf method can start searching.

For example, the following code snippet finds a string starting at the 3rd position in a String.

1 Console.WriteLine(authors.IndexOf("Naveen Sharma", 2));

The LastIndexOf method finds an item from the end of the List.

The following code snippet looks for a string in the backward direction and returns the index of the item if
found.

1 Console.WriteLine(authors.LastIndexOf("Mahesh Chand"));

The complete example is listed in Listing 7.

1 // List of string
2 List<string> authors = new List<string>(5);
3 authors.Add("Mahesh Chand");
4 authors.Add("Chris Love");
5 authors.Add("Allen O'neill");
6 authors.Add("Naveen Sharma");
7 authors.Add("Mahesh Chand");
8 authors.Add("Monica Rathbun");
9 authors.Add("David McCarter");
10 int idx = authors.IndexOf("Naveen Sharma");
11 if (idx > 0)
12 Console.WriteLine($"Item index in List is: {idx}");
13 else
14 Console.WriteLine("Item not found");
15 Console.WriteLine(authors.IndexOf("Naveen Sharma", 2));
16 Console.WriteLine(authors.LastIndexOf("Mahesh Chand"));

Listing 7.  

Sort a C# List

https://www.c-sharpcorner.com/article/c-sharp-list/[10/30/2024 12:34:31 PM]


C# List Tutorial - Everything You Need To Learn About List In C#

The Sort method of List <T> sorts all items of the List using the QuickSort algorithm.

The following code example in Listing eight sorts List items and displays both the original and sorted order
of the List items.

1 // List of string
2 List<string> authors = new List<string>(5);
3 authors.Add("Mahesh Chand");
4 authors.Add("Chris Love");
5 authors.Add("Allen O'neill");
6 authors.Add("Naveen Sharma");
7 authors.Add("Mahesh Chand");
8 authors.Add("Monica Rathbun");
9 authors.Add("David McCarter");
10 Console.WriteLine("Original List items");
11 Console.WriteLine("===============");
12 // Print original order
13 foreach (string a in authors)
14 Console.WriteLine(a);
15 // Sort list items
16 authors.Sort();
17 Console.WriteLine();
18 Console.WriteLine("Sorted List items");
19 Console.WriteLine("===============");
20 // Print sorted items
21 foreach (string a in authors)
22 Console.WriteLine(a);

Listing 8.

The output of Listing eight looks like Figure 2.

Figure 2.

Reverse a C# List
The Reverse method of List <T> reverses the order of all items in the List.

The following code snippet reverses a List.

1 // List of string

https://www.c-sharpcorner.com/article/c-sharp-list/[10/30/2024 12:34:31 PM]


C# List Tutorial - Everything You Need To Learn About List In C#

2 List<string> authors = new List<string>(5);


3 authors.Add("Mahesh Chand");
4 authors.Add("Chris Love");
5 authors.Add("Allen O'neill");
6 authors.Add("Naveen Sharma");
7 authors.Add("Mahesh Chand");
8 authors.Add("Monica Rathbun");
9 authors.Add("David McCarter");
10 Console.WriteLine("Original List items");
11 Console.WriteLine("===============");
12 // Print original order
13 foreach (string a in authors)
14 Console.WriteLine(a);
15 // Reverse list items
16 authors.Reverse();
17 Console.WriteLine();
18 Console.WriteLine("Sorted List items");
19 Console.WriteLine("===============");
20 // Print reversed items
21 foreach (string a in authors)
22 Console.WriteLine(a);

Listing 9.

The output of Listing nine looks like Figure 3.

Figure 3.

Find an Item in a C# List


The BinarySearch method of List <T> searches a sorted list and returns the zero-based index of the found
item. The List <T> must be sorted before this method can be used.

The following code snippet returns an index of a string in a List.

1 int bs = authors.BinarySearch("Mahesh Chand");

Import items to a C# List from another List


You can use the AddRange method of List to import items from one List into another list. But make sure the
item types are the same in both lists. For example, the following code snippet creates two List objects and

https://www.c-sharpcorner.com/article/c-sharp-list/[10/30/2024 12:34:31 PM]


C# List Tutorial - Everything You Need To Learn About List In C#

copies all items of listTwo into listOne.

1 // Program: Copy items from one list to another list


2 Console.WriteLine("Import one list to another!");
3
4 // Create List1
5 List<string> listOne = new();
6 listOne.Add("One");
7 listOne.Add("Two");
8 listOne.Add("Three");
9 listOne.Add("Four");
10 listOne.Add("Five");
11
12 // Create List2
13 List<string> listTwo = new();
14 listTwo.Add("A");
15 listTwo.Add("B");
16 listTwo.Add("C");
17
18 // Add List2 to List1
19 listOne.AddRange(listTwo);
20
21 // Display
22 foreach(string item in listOne)
23 Console.WriteLine(item);
24
25 Console.ReadKey();

Convert a C# List to an array


You can use the ToArray() method of the C# List class to convert a list into an array.

1 int[] a = number.ToArray();

Join two C# Lists


You can use the AddRange method to merge a C# List with an existing C# List. Here is a detailed article
on How to Merge Two C# Lists.

1 List1.AddRange(List2);

https://www.c-sharpcorner.com/article/c-sharp-list/[10/30/2024 12:34:31 PM]

You might also like