| by Arround The Web | No comments

Arrays vs Lists: Usage Comparison in C#

An array in C# is a set of items with identical data types and a defined specific size. It represents an adjoining chunk of memory where the elements are saved. Utilizing their index, the arrays in C# offer a quick and easy arbitrary access to their members. A list is a dynamic data structure in the C# programming language that represents a group of identically typed components. Unlike arrays, lists can grow or shrink in size dynamically which allows for the efficient addition, removal, and modification of elements. Both similarities and distinctions between C# arrays and C# lists are covered in this article.

Declaration:

Arrays are declared using the “type[] ArrayName;” syntax where the type signifies the type of the members in the array collection, and “ArrName” is the title that is assigned to the array. A declaration of an array is denoted by square brackets [].

type[] ArrayName = new type[];

Lists are declared using the “List<type> LsName;” syntax where the type represents the data type of the elements in the list, and “LsName” is the name that is given to the list. The angle brackets <type> indicate that it is a generic type declaration.

List<type> listName = new List<type>();

Initialization:

Arrays use curly braces {} to enclose the values, while lists use the new List<dataType> constructor followed by curly braces {} to enclose the values.

type[] ArrayName = { v1, v2, v3, ... };

List<type> listName = new List<type> { v1, v2, v3, ... };

Adding Values:

It’s crucial to remember that the C# arrays possess a specific size. If a different size is required, a new array “newArr” needs to be created with the desired size (current length + number of new values). Add the original array “OrgArr” to the new array and assign the new values to the new positions in the new array and update the reference to the new array.

Array.Copy(OrgArr, newArr, OrgArr.Length);

newArr[OrgArr.Length] = 14; // new value

newArr[OrgArr.Length + 1] = 2; // new value

OrgArr = newArr; // Update the reference int[] NewArr = new int[OrgArr.Length + 2];

Lists offer flexibility in terms of size management. When a list is initialized, it starts with an initial capacity, but it can expand automatically as more elements are added. This dynamic resizing capability allows the lists to adapt to changing requirements. The C# lists provide an Add() function to add the values to the list. Here’s how you can add values to a C# list:

Arrays vs Lists: Usage Comparison in C#

Accessing the Values

The values in the array numbers are accessed using the index notation [], i.e. using the index number in the brackets and is saved to another variable.

type element = ArrayName[index];

To access the values in a C# list, you can also use the index notation [] along with the desired index position similar to arrays.

type element = ListName[index];

Removing the Values

Arrays have a set length. Therefore, to remove the elements, a new array must be created with a lesser size, and the existing elements must be copied. This may be done by employing the Array.Copy() function as explained in the “Adding Values” section. In C# lists, removing the values is much simpler and more intuitive. The List<T> class provides a “remove” method that allows you to remove a specific value from the list.

listName.Remove(element);

Count the Values

To count the values in a C# array, you may employ the array’s length attribute. The length property gives you the total number of values in the array.

int count = arrayName.Length;

To count the values in a C# list, you can employ the list’s “count” feature. The total amount of elements that currently reside in the list is likewise returned by the “count” attribute.

int count = listName.Count;

Iterate the Values

To iterate over values in a C# array, you can use a “for” loop with the array’s length as the loop condition.

for (int i = 0; i < ArrayName.Length; i++) {

  type e = arrayName[i];

  Console.WriteLine(e);

}

To iterate over the values in a C# list, you can use a “foreach” loop as it simplifies the iteration process by automatically iterating over the elements.

foreach (type e in listName) {

  Console.WriteLine(e);

}

Example 1: C# Arrays

The given code declares and initializes an integer array named “Arr” with a length of 5 and assigns the values to its elements. The assigned values to the array elements are 11, 12, 13, 14, and 15. The code then proceeds to display the elements of the array using a “for” loop. Every component is displayed on a distinct line using the Console.WriteLine() method.

After displaying the original elements, the code modifies the element at index 2 by assigning it with a new value of 10. Next, the code displays the modified array by iterating through the elements again using a “for” loop. Lastly, the code displays the total number of values that reside in the array using the “Arr.Length” property which yields the length of the array.

using System;

class Dummy {

  static void Main() {

    int[] Arr = new int[5] { 11, 12, 13, 14, 15 };

    Console.WriteLine("Elements:");

    for (int i = 0; i < Arr.Length; i++)

    {

      Console.WriteLine(Arr[i]);

    }

    Arr[2] = 10;

    Console.WriteLine("Modified array:");

    for (int i = 0; i < Arr.Length; i++)

    {

      Console.WriteLine(Arr[i]);

    }

    Console.WriteLine("Number of elements: " + Arr.Length);

  }

}

Example 2: C# Lists

The following provided code demonstrates the usage of a C# list to store and manipulate a collection of integers. First, the code initializes a list named “Arr” with five integers: 11, 12, 13, 14, and 15. This is achieved using the List<T> class and its constructor along with an initializer syntax.

Next, the program prints the “Elements:” message and proceeds to iterate over each element in the list using a “foreach” loop. During each iteration, the current element is printed to the console using the Console.WriteLine() method.

Afterward, the code modifies the value at index 2 of the list by assigning it with the value of 10 (Arr[2] = 10). This line changes the third element in the list from 13 to 10. Following the modification, the program again prints the “Modified list:” message and iterates over the updated list, printing each element to the console. The code then displays the number of values in the list using “Arr.Count”. This property returns the count of items that are present in the list which, in the following scenario, happens to be 5.

Lastly, the code removes the element with the value of 4 from the list using the Arr.Remove(4) method. This method searches for the specified value in the list and removes its first occurrence. Finally, the program prints the “List after removal:” message and iterates over the list once more, displaying each remaining element after the removal operation.

using System;

using System.Collections.Generic;

class Dummy {

  static void Main() {

    List<int> Arr = new List<int>() { 11, 12, 13, 14, 15 };
 
    Console.WriteLine("Elements:");

    foreach (int n in Arr)

    {

        Console.WriteLine(n);

    }

    Arr[2] = 10;

    Console.WriteLine("Modified list:");

    foreach (int n in Arr)

    {

        Console.WriteLine(n);

    }

    Console.WriteLine("Number of elements: " + Arr.Count);

    Arr.Remove(4);

    Console.WriteLine("List after removal:");

    foreach (int n in Arr)

    {

        Console.WriteLine(n);

    }

  }

}

Conclusion

This guide covered the basic syntax differences between the C# arrays and C# lists. The arrays have fixed length and are accessed by index, whereas the lists are dynamically sized and provide additional methods to add and remove the elements. Along with that, we provided the C# list programs that showcase the declaration, initialization, accessing, modifying, counting, and adding the elements.

Share Button

Source: linuxhint.com

Leave a Reply