Lists

The List collection type is much easier to use than an array, however, it has the same performance limitations.


Initialize a List

There are couple ways to initialize a list.

List<string> students = new List<string>();
List<string> students = new List<string>() {"Sue", "Bill"};
List<int> numbers = new List<int>();

Inserting data in List

students.Add("Sue");
students.Add("Bill");
students.Add("Joko");

// result:
// { "Sue", "Bill", "Joko" }

Accessing data in List

Accesing the data in list is pretty simple, just call the index of the array.

students[2] //result: Joko

Updating data in List

Updating the data acts as adding the data in array. Updating means replacing the current data in array.

List<int> numbers = new List<int>();
numbers[0] = 10; //store 10 in list index 0
numbers[0] = 20; //list contains 20 in index 0

Deleting data in List

Code shown below will deleting data in list

students.RemoveAt(1); // Bill deleted
students.RemoveRange(0, 1); // Delete an index from 0 to 1
students.Remove("Sue"); // Sue deleted

If we need to store a data which larger than array size, we have to create a new larger array and perform CopyTo method, while List does it automatically. In short, List will expand its capacity twice than before and copy all of items when the amount of data reach previous maximum capacity. So, List aren't necessarily more efficient than arrays in terms of performance.

More List Operations

Looping data in list.

foreach (string student in students) {
    Console.WriteLine(student);
}

// Result:
// Sue
// Bill
// Joko

Inserting data to list.

students.Insert(1, "Frank");

// Result:
// { "Sue", "Frank", "Bill", "Joko" }

Sorting a list.

students.Sort();

// Result: {"Bill", "Frank", "Joko", "Sue"}

Searching the index of list.

students.BinarySearch("Frank"); // result: 1
students.BinarySearch("Alan"); // result: -1
students.BinarySearch("Kiki"); // result: -4

results matching ""

    No results matching ""