Lists

While working on arrays, we learned that the length of an array must be specified when the array is declared. Also, we cannot increase the length of an array collection. 

To overcome these issues, we can use the list collection. Lists provide us with several helper methods that help us to add and remove items in a list, sort a list, search in a list, and more. A list collection is declared by the following index:

 List<int> vs = new List<int>();

If we go to the definition of a list, we will realize that, internally, it implements many interfaces, such as IEnumerable, ICollection, and IList. Due to these different interfaces, list collections are extremely powerful and provide different operations. The following screenshot shows what the definition of a list collection looks like in .NET:

The IEnumerable interface allows us to loop through the list collection using the foreach loop just as we did for arrays. The ICollection interface allows us to do operations such as count length, add a new element, and remove an element.

Let's look at the following code implementation, in which we will execute all of these operations on the list:

public static void ListCollectionOperations()
{
List<int> vs = new List<int> { 1, 2, 3, 4, 5, 6 };
for (int x = 0; x < vs.Count; x++)
Console.Write(vs[x]);
vs.Remove(1);
Console.WriteLine(vs[0]);
vs.Add(7);
Console.WriteLine(vs.Count);
bool doesExist = vs.Contains(4);
Console.WriteLine(doesExist);
}

Let's look at what we did in the preceding code:

  • We have created a list of int and added the elements 1-6.
  • We are looping across the list using a for loop and we are printing the values present in it. To find the length or the number of elements present in a list, we are using the Count property.
  • To remove an element from a particular index, we can use the Remove method. In the preceding code implementation, we are removing the element present at index 1.
  • To add a new element in the list, we use the Add method. In the preceding code implementation, we are adding an element, 7, to the list.
  • To check whether an element is present in the list, we use the Contains method. In the preceding code implementation, we are checking whether a 4 element is present in the list.

If we execute this, we get the following output:

One potential issue with a list collection is that we can have duplicate values in the list. For example, in the preceding example, it's possible to have two elements with the same value as 1 in the list. 

Due to this issue, we cannot use list collection in scenarios where we must ensure the uniqueness of values. In the next section, we will look at another collection dictionary that overcomes this issue with a list object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.110.155