Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Métodos de Listas | Estruturas de Dados e Manipulação de Arquivos
C# Além do Básico

bookMétodos de Listas

Neste capítulo, serão abordados alguns métodos úteis de listas.

Remove()

O método Remove remove a primeira ocorrência de um elemento de uma lista.

Sintaxe:

exampleList.remove(targetElement);
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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 + " "); } } } }

Caso tal elemento não seja encontrado, nenhuma ação será realizada.

index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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()

O método RemoveAt remove um elemento em um índice específico.

Sintaxe:

exampleList.RemoveAt(index);
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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

O método Clear remove todos os elementos de uma lista. Não recebe argumentos.

Sintaxe:

exampleList.Clear();
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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

O método Insert insere um elemento na lista em um índice especificado.

Sintaxe:

exampleList.Insert(index, elementToInsert);
index.cs

index.cs

copy
1234567891011121314151617181920212223
using 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 + " "); } } }

É possível omitir as chaves {} caso haja apenas uma única instrução dentro de uma condição if, um laço for ou um laço foreach.

index.cs

index.cs

copy
123
foreach(int number in numbers) { Console.Write(number + " "); }

O trecho acima é equivalente a:

index.cs

index.cs

copy
12
foreach(int number in numbers) Console.Write(number + " ");

Se já houver um elemento no índice especificado, ele será deslocado para a direita, assim como os demais elementos do array após ele, caso existam. O diagrama a seguir ilustra esse processo:

Contains()

O método Contains verifica se uma lista contém um elemento específico. Retorna um valor booleano (true ou false).

Sintaxe: exampleList.Contains(element);

index.cs

index.cs

copy
1234567891011121314
using 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()

O método IndexOf retorna o índice da primeira ocorrência de um elemento em uma lista.

Sintaxe: exampleList.IndexOf(element);

index.cs

index.cs

copy
123456789101112131415
using 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')); } } }

Se o elemento não existir na lista, simplesmente retorna -1:

O método indexOf é especialmente útil quando se deseja acessar um elemento pelo índice, mas não se conhece o índice. Na lista vowels, deseja-se acessar o elemento o pelo índice e alterá-lo para o O maiúsculo:

index.cs

index.cs

copy
12345678910111213141516171819
using 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. O que o método Remove() faz?

2. Qual é a maneira mais rápida de verificar se uma lista contém um elemento específico?

3. Qual método é utilizado para remover todos os elementos de uma lista?

4. Qual será a saída do seguinte código?

question mark

O que o método Remove() faz?

Select the correct answer

question mark

Qual é a maneira mais rápida de verificar se uma lista contém um elemento específico?

Select the correct answer

question mark

Qual método é utilizado para remover todos os elementos de uma lista?

Select the correct answer

question mark

Qual será a saída do seguinte código?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Awesome!

Completion rate improved to 2.04

bookMétodos de Listas

Deslize para mostrar o menu

Neste capítulo, serão abordados alguns métodos úteis de listas.

Remove()

O método Remove remove a primeira ocorrência de um elemento de uma lista.

Sintaxe:

exampleList.remove(targetElement);
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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 + " "); } } } }

Caso tal elemento não seja encontrado, nenhuma ação será realizada.

index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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()

O método RemoveAt remove um elemento em um índice específico.

Sintaxe:

exampleList.RemoveAt(index);
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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

O método Clear remove todos os elementos de uma lista. Não recebe argumentos.

Sintaxe:

exampleList.Clear();
index.cs

index.cs

copy
123456789101112131415161718192021222324252627
using 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

O método Insert insere um elemento na lista em um índice especificado.

Sintaxe:

exampleList.Insert(index, elementToInsert);
index.cs

index.cs

copy
1234567891011121314151617181920212223
using 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 + " "); } } }

É possível omitir as chaves {} caso haja apenas uma única instrução dentro de uma condição if, um laço for ou um laço foreach.

index.cs

index.cs

copy
123
foreach(int number in numbers) { Console.Write(number + " "); }

O trecho acima é equivalente a:

index.cs

index.cs

copy
12
foreach(int number in numbers) Console.Write(number + " ");

Se já houver um elemento no índice especificado, ele será deslocado para a direita, assim como os demais elementos do array após ele, caso existam. O diagrama a seguir ilustra esse processo:

Contains()

O método Contains verifica se uma lista contém um elemento específico. Retorna um valor booleano (true ou false).

Sintaxe: exampleList.Contains(element);

index.cs

index.cs

copy
1234567891011121314
using 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()

O método IndexOf retorna o índice da primeira ocorrência de um elemento em uma lista.

Sintaxe: exampleList.IndexOf(element);

index.cs

index.cs

copy
123456789101112131415
using 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')); } } }

Se o elemento não existir na lista, simplesmente retorna -1:

O método indexOf é especialmente útil quando se deseja acessar um elemento pelo índice, mas não se conhece o índice. Na lista vowels, deseja-se acessar o elemento o pelo índice e alterá-lo para o O maiúsculo:

index.cs

index.cs

copy
12345678910111213141516171819
using 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. O que o método Remove() faz?

2. Qual é a maneira mais rápida de verificar se uma lista contém um elemento específico?

3. Qual método é utilizado para remover todos os elementos de uma lista?

4. Qual será a saída do seguinte código?

question mark

O que o método Remove() faz?

Select the correct answer

question mark

Qual é a maneira mais rápida de verificar se uma lista contém um elemento específico?

Select the correct answer

question mark

Qual método é utilizado para remover todos os elementos de uma lista?

Select the correct answer

question mark

Qual será a saída do seguinte código?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 3
some-alt