Lists in C#

Previously, I already wrote a post about arrays y listas en C#, but in this series I will do several posts about collections, so I feel it’s necessary to mention lists, with a bit more detail. 

 

1 - What is the List type in C#

When working in C#, one of the most frequently used elements is the type List<T> because it allows us to list elements, but not only that, we can also sort, filter, search, and more.

 

Before continuing, I want to mention the ArrayList type, which might sound more familiar if you're coming from other languages like Java. Basically, ArrayList is the same as List<T> but it does not use generics.

 

 

2 - Creating a list and adding elements in C#

To create a list, you just need to instantiate it with new. Alternatively, it’s very common to already have another collection or an array and use the extension method .ToArray().

 

During initialization, we can also create the list’s elements.

To add elements, we can include them one by one using .Add(), or if we already have another list or array created, we can use .AddRange().

//Iniciación, asignando valores
List<string> firstList = new List<string>()
{
    "Opel",
    "BMW"
};

List<string> marcas = new List<string>();
//Añadir un elemento
marcas.Add("Audi");
//Añadir una lista a otra lista
marcas.AddRange(firstList);

 

 

3 - Accessing elements in a list

To access elements in a list, we do so by index -- through the indexer

For this, we directly indicate the element to access, or we can iterate through them with a foreach loop

Console.WriteLine(marcas[0]); //Audi

foreach (string item in marcas)
    Console.WriteLine(item);

 

 

4 - Lists and collections in C#

When working with a list, it is completely mutable, meaning we can add, remove, move elements, etc. If you do not need any of this, I recommend converting the list to immutable, either converting it to IList<T> or to ReadonlyList<T>.

  • note: there is "no" particular preference as to which to use, maybe the readonly version is easier to read, but they perform the same functions. An interesting fact is that ReadOnly collections were introduced in .net framework 4.5 while IList<T> already existed earlier. That said, they are not interchangeable, as they do not implement each other.
IReadOnlyList<string> readonlyMarcas = marcas;
IList<string> IlistMarcas = marcas;

 

4.1 - Insert elements into a list

Besides the .Add() and .AddRange methods, we can insert elements using the .Insert() method, which, by specifying the index, lets us define which element and where we want to add it.

marcas.Insert(1, "Skoda");

 

4.2 - Remove elements from a list

To remove elements from a list, we have two options: the first is to remove by index using .RemoveAt(index)

And the second is to remove by specifying the element to remove, using .Remove(T):

marcas.RemoveAt(0); //Elimina Audi
marcas.Remove("Skoda");//Elimina skoda

Finally, there’s another option, .RemoveAll(), which removes all elements.

 

4.3 - More options with lists

List functionality doesn’t end there, we can use the .Count property, or take advantage of a wide range of methods, such as .Clear() to clear the list, .Find() to find elements using a predicate, or .Sort() to sort.

 

 

5 - What is SortedList in C#?

Before wrapping up, I’d like to give a special mention to SortedList. Honestly, I could write a whole post just about this type, but I’ve actually never needed it in the workplace, so a mention should suffice. 

 

SortedList allows us to specify a key element, which acts as the index or comparison element, and the value itself; the type is described as SortedList<TKey, TValue>. It uses the IComparer interface to compare elements. (I’ll write a post about that interface in the future.)

 

Once you insert an element, it’s sorted automatically.

SortedList<int, string> listaCochesOrdenada = new SortedList<int, string>()
{
    {3,"bmw" },
    {1, "audi" },
    {2, "opel" }
};

foreach (var item in listaCochesOrdenada)
    Console.WriteLine(item.Value); //imprime: audi, opel, bmw

 

 

Conclusion

In this post, we’ve seen how to create lists in C#.

We’ve seen how to insert elements in a list in C#.

We’ve seen how to remove elements from a list in C#.

We’ve discussed what the SortedList type is in C#.

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café