In this article, we will learn about the List class.
The List
We create a list in C# using the following syntax:
List<T> l1 = new List<T>();
<T>
here denotes any datatype of which we want to create a list of.
Count
: This property gets the number of nodes actually contained in the ListCapacity
: Gets or sets the total number of elements the internal data structure can hold without resizing..List[Int32]
: Gets or sets the element at the specified index.Add(T)
: Adds the element at the end of the ListAddRange(IEnumerable)</code>: Adds the elements of the specified collection to the end of the List.</li>
Contains(T)
: Determines whether a value is in the List.</li>
Remove(T)
: Removes the first occurrence of the specified value from the List.</li>
RemoveAt(ind)
: Removes the element at the specified index.
Sort()
: Sorts the elements in the entire List using the default comparer.</li>
Insert(ind, T)
: Inserts T at the specified index.
Clear()
: Removes all the elements from the List.</li>
</ul>
List Operation Examples:
Different List operations are demonstrated in the example below:
using System;
using System.Collections.Generic;
namespace ListDemo {
class Example {
static void Main(string[] args) {
List < int > L = new List < int > ();
L.Add(5); // Adds to the end
L.Add(2);
L.Add(4);
L.Add(9);
foreach(int i in L) {
Console.Write(i + " ");
}
Console.WriteLine();
L.Sort(); // Sorts the list in ascending order
foreach(int i in L) {
Console.Write(i + " ");
}
Console.WriteLine();
L.RemoveAt(1); // Removes the elements from the 1st index
L.Remove(9); // Removes first occurenece of 9
foreach(int i in L) {
Console.Write(i + " ");
}
Console.WriteLine();
Console.WriteLine(L.Contains(2)); // Checks if 2 is present in the list
Console.WriteLine(L.Count); // Count returns the number of elements present
}
}
}
Output:
5 2 4 9
2 4 5 9
2 5
True
2
Task
In the editor below, perform the different tasks as directed.