Métodos de Listas
En este capítulo se revisarán algunos métodos útiles de listas.
Remove()
El método Remove
elimina la primera instancia de un elemento de una lista.
Sintaxis:
exampleList.remove(targetElement);
index.cs
123456789101112131415161718192021222324252627using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Remove("Banana"); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }
En caso de que no se encuentre dicho elemento, simplemente no realiza ninguna acción.
index.cs
123456789101112131415161718192021222324252627using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Remove("some element"); // trying to remove an unknown element Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }
RemoveAt()
El método RemoveAt
elimina un elemento en un índice específico.
Sintaxis:
exampleList.RemoveAt(index);
index.cs
123456789101112131415161718192021222324252627using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.RemoveAt(1); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }
Clear
El método Clear
elimina todos los elementos de una lista. No recibe argumentos.
Sintaxis:
exampleList.Clear();
index.cs
123456789101112131415161718192021222324252627using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Clear(); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }
Insert
El método Insert
inserta un elemento en la lista en un índice especificado.
Sintaxis:
exampleList.Insert(index, elementToInsert);
index.cs
1234567891011121314151617181920212223using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<int> numbers = new List<int> { 2, 4, 6, 10, 12 }; Console.Write("Before: "); foreach (int number in numbers) Console.Write(number + " "); numbers.Insert(3, 8); Console.Write("\nAfter: "); foreach (int number in numbers) Console.Write(number + " "); } } }
Se pueden omitir las llaves {}
si solo hay una instrucción dentro de una condición if
, un bucle for
o un bucle foreach
.
index.cs
123foreach(int number in numbers) { Console.Write(number + " "); }
El fragmento anterior es equivalente a:
index.cs
12foreach(int number in numbers) Console.Write(number + " ");
Si ya existe un elemento en el índice especificado, este se desplaza hacia la derecha, al igual que los elementos restantes del arreglo que le siguen, en caso de haberlos. El siguiente diagrama ilustra el proceso:

Contains()
El método Contains
verifica si una lista contiene un elemento específico. Devuelve un valor booleano (true
o false
).
Sintaxis: exampleList.Contains(element);
index.cs
1234567891011121314using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; Console.WriteLine("Contains 'o': " + vowels.Contains('o')); } } }
IndexOf()
El método IndexOf
devuelve el índice de la primera aparición de un elemento en una lista.
Sintaxis: exampleList.IndexOf(element);
index.cs
123456789101112131415using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; vowels.Remove('o'); Console.WriteLine("Index of 'o': " + vowels.IndexOf('o')); } } }
Si el elemento no existe en la lista, simplemente devuelve -1
:
El método indexOf
es especialmente útil cuando se desea acceder a un elemento por índice pero no se conoce su índice. En vowels
, se desea acceder al elemento o
por índice y cambiarlo a la O
mayúscula:
index.cs
12345678910111213141516171819using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; int targetIndex = vowels.IndexOf('o'); Console.WriteLine(vowels[targetIndex]); vowels[targetIndex] = 'O'; Console.WriteLine(vowels[targetIndex]); } } }
1. ¿Qué hace el método Remove()
?
2. ¿Cuál es la forma más rápida de comprobar si una lista contiene un elemento específico?
3. ¿Qué método se utiliza para eliminar todos los elementos de una lista?
4. ¿Cuál será la salida del siguiente código?
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 2.04
Métodos de Listas
Desliza para mostrar el menú
En este capítulo se revisarán algunos métodos útiles de listas.
Remove()
El método Remove
elimina la primera instancia de un elemento de una lista.
Sintaxis:
exampleList.remove(targetElement);
index.cs
123456789101112131415161718192021222324252627using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Remove("Banana"); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }
En caso de que no se encuentre dicho elemento, simplemente no realiza ninguna acción.
index.cs
123456789101112131415161718192021222324252627using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Banana", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Remove("some element"); // trying to remove an unknown element Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }
RemoveAt()
El método RemoveAt
elimina un elemento en un índice específico.
Sintaxis:
exampleList.RemoveAt(index);
index.cs
123456789101112131415161718192021222324252627using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.RemoveAt(1); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }
Clear
El método Clear
elimina todos los elementos de una lista. No recibe argumentos.
Sintaxis:
exampleList.Clear();
index.cs
123456789101112131415161718192021222324252627using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<string> fruits = new List<string> { "Apple", "Orange", "Banana", "Grape" }; Console.Write("Before: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } fruits.Clear(); Console.Write("\nAfter: "); foreach (string fruit in fruits) { Console.Write(fruit + " "); } } } }
Insert
El método Insert
inserta un elemento en la lista en un índice especificado.
Sintaxis:
exampleList.Insert(index, elementToInsert);
index.cs
1234567891011121314151617181920212223using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<int> numbers = new List<int> { 2, 4, 6, 10, 12 }; Console.Write("Before: "); foreach (int number in numbers) Console.Write(number + " "); numbers.Insert(3, 8); Console.Write("\nAfter: "); foreach (int number in numbers) Console.Write(number + " "); } } }
Se pueden omitir las llaves {}
si solo hay una instrucción dentro de una condición if
, un bucle for
o un bucle foreach
.
index.cs
123foreach(int number in numbers) { Console.Write(number + " "); }
El fragmento anterior es equivalente a:
index.cs
12foreach(int number in numbers) Console.Write(number + " ");
Si ya existe un elemento en el índice especificado, este se desplaza hacia la derecha, al igual que los elementos restantes del arreglo que le siguen, en caso de haberlos. El siguiente diagrama ilustra el proceso:

Contains()
El método Contains
verifica si una lista contiene un elemento específico. Devuelve un valor booleano (true
o false
).
Sintaxis: exampleList.Contains(element);
index.cs
1234567891011121314using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; Console.WriteLine("Contains 'o': " + vowels.Contains('o')); } } }
IndexOf()
El método IndexOf
devuelve el índice de la primera aparición de un elemento en una lista.
Sintaxis: exampleList.IndexOf(element);
index.cs
123456789101112131415using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; vowels.Remove('o'); Console.WriteLine("Index of 'o': " + vowels.IndexOf('o')); } } }
Si el elemento no existe en la lista, simplemente devuelve -1
:
El método indexOf
es especialmente útil cuando se desea acceder a un elemento por índice pero no se conoce su índice. En vowels
, se desea acceder al elemento o
por índice y cambiarlo a la O
mayúscula:
index.cs
12345678910111213141516171819using System; using System.Collections.Generic; namespace ConsoleApp { class Program { static void Main(string[] args) { List<char> vowels = new List<char> { 'a', 'e', 'i', 'o', 'u' }; int targetIndex = vowels.IndexOf('o'); Console.WriteLine(vowels[targetIndex]); vowels[targetIndex] = 'O'; Console.WriteLine(vowels[targetIndex]); } } }
1. ¿Qué hace el método Remove()
?
2. ¿Cuál es la forma más rápida de comprobar si una lista contiene un elemento específico?
3. ¿Qué método se utiliza para eliminar todos los elementos de una lista?
4. ¿Cuál será la salida del siguiente código?
¡Gracias por tus comentarios!