StringCollection Classe

Definição

Representa uma coleção de cordas.

public ref class StringCollection : System::Collections::IList
public class StringCollection : System.Collections.IList
[System.Serializable]
public class StringCollection : System.Collections.IList
type StringCollection = class
    interface ICollection
    interface IEnumerable
    interface IList
[<System.Serializable>]
type StringCollection = class
    interface IList
    interface ICollection
    interface IEnumerable
Public Class StringCollection
Implements IList
Herança
StringCollection
Derivado
Atributos
Implementações

Exemplos

O exemplo de código seguinte demonstra várias das propriedades e métodos de StringCollection.

using System;
using System.Collections;
using System.Collections.Specialized;

public class SamplesStringCollection  {

   public static void Main()  {

      // Create and initializes a new StringCollection.
      StringCollection myCol = new StringCollection();

      // Add a range of elements from an array to the end of the StringCollection.
      String[] myArr = new String[] { "RED", "orange", "yellow", "RED", "green", "blue", "RED", "indigo", "violet", "RED" };
      myCol.AddRange( myArr );

      // Display the contents of the collection using foreach. This is the preferred method.
      Console.WriteLine( "Displays the elements using foreach:" );
      PrintValues1( myCol );

      // Display the contents of the collection using the enumerator.
      Console.WriteLine( "Displays the elements using the IEnumerator:" );
      PrintValues2( myCol );

      // Display the contents of the collection using the Count and Item properties.
      Console.WriteLine( "Displays the elements using the Count and Item properties:" );
      PrintValues3( myCol );

      // Add one element to the end of the StringCollection and insert another at index 3.
      myCol.Add( "* white" );
      myCol.Insert( 3, "* gray" );

      Console.WriteLine( "After adding \"* white\" to the end and inserting \"* gray\" at index 3:" );
      PrintValues1( myCol );

      // Remove one element from the StringCollection.
      myCol.Remove( "yellow" );

      Console.WriteLine( "After removing \"yellow\":" );
      PrintValues1( myCol );

      // Remove all occurrences of a value from the StringCollection.
      int i = myCol.IndexOf( "RED" );
      while ( i > -1 )  {
         myCol.RemoveAt( i );
         i = myCol.IndexOf( "RED" );
      }

      // Verify that all occurrences of "RED" are gone.
      if ( myCol.Contains( "RED" ) )
         Console.WriteLine( "*** The collection still contains \"RED\"." );

      Console.WriteLine( "After removing all occurrences of \"RED\":" );
      PrintValues1( myCol );

      // Copy the collection to a new array starting at index 0.
      String[] myArr2 = new String[myCol.Count];
      myCol.CopyTo( myArr2, 0 );

      Console.WriteLine( "The new array contains:" );
      for ( i = 0; i < myArr2.Length; i++ )  {
         Console.WriteLine( "   [{0}] {1}", i, myArr2[i] );
      }
      Console.WriteLine();

      // Clears the entire collection.
      myCol.Clear();

      Console.WriteLine( "After clearing the collection:" );
      PrintValues1( myCol );
   }

   // Uses the foreach statement which hides the complexity of the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues1( StringCollection myCol )  {
      foreach ( Object obj in myCol )
         Console.WriteLine( "   {0}", obj );
      Console.WriteLine();
   }

   // Uses the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues2( StringCollection myCol )  {
      StringEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.WriteLine( "   {0}", myEnumerator.Current );
      Console.WriteLine();
   }

   // Uses the Count and Item properties.
   public static void PrintValues3( StringCollection myCol )  {
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( "   {0}", myCol[i] );
      Console.WriteLine();
   }
}

/*
This code produces the following output.

Displays the elements using foreach:
   RED
   orange
   yellow
   RED
   green
   blue
   RED
   indigo
   violet
   RED

Displays the elements using the IEnumerator:
   RED
   orange
   yellow
   RED
   green
   blue
   RED
   indigo
   violet
   RED

Displays the elements using the Count and Item properties:
   RED
   orange
   yellow
   RED
   green
   blue
   RED
   indigo
   violet
   RED

After adding "* white" to the end and inserting "* gray" at index 3:
   RED
   orange
   yellow
   * gray
   RED
   green
   blue
   RED
   indigo
   violet
   RED
   * white

After removing "yellow":
   RED
   orange
   * gray
   RED
   green
   blue
   RED
   indigo
   violet
   RED
   * white

After removing all occurrences of "RED":
   orange
   * gray
   green
   blue
   indigo
   violet
   * white

The new array contains:
   [0] orange
   [1] * gray
   [2] green
   [3] blue
   [4] indigo
   [5] violet
   [6] * white

After clearing the collection:

*/
Imports System.Collections
Imports System.Collections.Specialized

Public Class SamplesStringCollection

   Public Shared Sub Main()

      ' Create and initializes a new StringCollection.
      Dim myCol As New StringCollection()

      ' Add a range of elements from an array to the end of the StringCollection.
      Dim myArr() As String = {"RED", "orange", "yellow", "RED", "green", "blue", "RED", "indigo", "violet", "RED"}
      myCol.AddRange(myArr)

      ' Display the contents of the collection using foreach. This is the preferred method.
      Console.WriteLine("Displays the elements using foreach:")
      PrintValues1(myCol)

      ' Display the contents of the collection using the enumerator.
      Console.WriteLine("Displays the elements using the IEnumerator:")
      PrintValues2(myCol)

      ' Display the contents of the collection using the Count and Item properties.
      Console.WriteLine("Displays the elements using the Count and Item properties:")
      PrintValues3(myCol)

      ' Add one element to the end of the StringCollection and insert another at index 3.
      myCol.Add("* white")
      myCol.Insert(3, "* gray")

      Console.WriteLine("After adding ""* white"" to the end and inserting ""* gray"" at index 3:")
      PrintValues1(myCol)

      ' Remove one element from the StringCollection.
      myCol.Remove("yellow")

      Console.WriteLine("After removing ""yellow"":")
      PrintValues1(myCol)

      ' Remove all occurrences of a value from the StringCollection.
      Dim i As Integer = myCol.IndexOf("RED")
      While i > - 1
         myCol.RemoveAt(i)
         i = myCol.IndexOf("RED")
      End While

      ' Verify that all occurrences of "RED" are gone.
      If myCol.Contains("RED") Then
         Console.WriteLine("*** The collection still contains ""RED"".")
      End If 
      Console.WriteLine("After removing all occurrences of ""RED"":")
      PrintValues1(myCol)

      ' Copy the collection to a new array starting at index 0.
      Dim myArr2(myCol.Count) As String
      myCol.CopyTo(myArr2, 0)

      Console.WriteLine("The new array contains:")
      For i = 0 To myArr2.Length - 1
         Console.WriteLine("   [{0}] {1}", i, myArr2(i))
      Next i
      Console.WriteLine()

      ' Clears the entire collection.
      myCol.Clear()

      Console.WriteLine("After clearing the collection:")
      PrintValues1(myCol)
   End Sub


   ' Uses the foreach statement which hides the complexity of the enumerator.
   ' NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   Public Shared Sub PrintValues1(myCol As StringCollection)
      Dim obj As [Object]
      For Each obj In  myCol
         Console.WriteLine("   {0}", obj)
      Next obj
      Console.WriteLine()
   End Sub


   ' Uses the enumerator. 
   ' NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   Public Shared Sub PrintValues2(myCol As StringCollection)
      Dim myEnumerator As StringEnumerator = myCol.GetEnumerator()
      While myEnumerator.MoveNext()
         Console.WriteLine("   {0}", myEnumerator.Current)
      End While
      Console.WriteLine()
   End Sub


   ' Uses the Count and Item properties.
   Public Shared Sub PrintValues3(myCol As StringCollection)
      Dim i As Integer
      For i = 0 To myCol.Count - 1
         Console.WriteLine("   {0}", myCol(i))
      Next i
      Console.WriteLine()
   End Sub

End Class


'This code produces the following output.
'
'Displays the elements using foreach:
'   RED
'   orange
'   yellow
'   RED
'   green
'   blue
'   RED
'   indigo
'   violet
'   RED
'
'Displays the elements using the IEnumerator:
'   RED
'   orange
'   yellow
'   RED
'   green
'   blue
'   RED
'   indigo
'   violet
'   RED
'
'Displays the elements using the Count and Item properties:
'   RED
'   orange
'   yellow
'   RED
'   green
'   blue
'   RED
'   indigo
'   violet
'   RED
'
'After adding "* white" to the end and inserting "* gray" at index 3:
'   RED
'   orange
'   yellow
'   * gray
'   RED
'   green
'   blue
'   RED
'   indigo
'   violet
'   RED
'   * white
'
'After removing "yellow":
'   RED
'   orange
'   * gray
'   RED
'   green
'   blue
'   RED
'   indigo
'   violet
'   RED
'   * white
'
'After removing all occurrences of "RED":
'   orange
'   * gray
'   green
'   blue
'   indigo
'   violet
'   * white
'
'The new array contains:
'   [0] orange
'   [1] * gray
'   [2] green
'   [3] blue
'   [4] indigo
'   [5] violet
'   [6] * white
'
'After clearing the collection:
'

Observações

StringCollection aceita null como valor válido e permite elementos duplicados.

As comparações de cadeias são sensíveis às maiúsculas e minúsculas.

Os elementos desta coleção podem ser acessados usando um índice inteiro. Os índices nesta coleção são baseados em zero.

Construtores

Name Description
StringCollection()

Inicializa uma nova instância da StringCollection classe.

Propriedades

Name Description
Count

Obtém o número de cadeias contidas no StringCollection.

IsReadOnly

Recebe um valor que indica se o StringCollection é apenas de leitura.

IsSynchronized

Recebe um valor que indica se o acesso ao StringCollection é sincronizado (thread safe).

Item[Int32]

Obtém ou define o elemento no índice especificado.

SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso ao StringCollection.

Métodos

Name Description
Add(String)

Adiciona uma cadeia ao final do StringCollection.

AddRange(String[])

Copia os elementos de um array de cadeias para o final do StringCollection.

Clear()

Remove todas as cadeias do StringCollection.

Contains(String)

Determina se a cadeia especificada pertence à StringCollection.

CopyTo(String[], Int32)

Copia todos StringCollection os valores para um array unidimensional de cadeias, começando no índice especificado do array alvo.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetEnumerator()

Devolve um StringEnumerator que itera através do StringCollection.

GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IndexOf(String)

Procura a cadeia especificada e devolve o índice baseado em zero da primeira ocorrência dentro do StringCollection.

Insert(Int32, String)

Insere uma sequência no StringCollection índice especificado.

MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
Remove(String)

Remove a primeira ocorrência de uma cadeia específica do StringCollection.

RemoveAt(Int32)

Remove a cadeia no índice especificado do StringCollection.

ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Implementações de Interface Explícita

Name Description
ICollection.CopyTo(Array, Int32)

Copia a totalidade StringCollection para uma unidimensional Arraycompatível , começando no índice especificado do array alvo.

IEnumerable.GetEnumerator()

Devolve um IEnumerator que itera através do StringCollection.

IList.Add(Object)

Adiciona um objeto ao final do StringCollection.

IList.Contains(Object)

Determina se um elemento pertence ao StringCollection.

IList.IndexOf(Object)

Procura o especificado Object e devolve o índice baseado em zero da primeira ocorrência dentro de todo StringCollectiono .

IList.Insert(Int32, Object)

Insere um elemento no StringCollection índice especificado.

IList.IsFixedSize

Recebe um valor que indica se o StringCollection objeto tem um tamanho fixo.

IList.IsReadOnly

Recebe um valor que indica se o StringCollection objeto é apenas de leitura.

IList.Item[Int32]

Obtém ou define o elemento no índice especificado.

IList.Remove(Object)

Remove a primeira ocorrência de um objeto específico do StringCollection.

Métodos da Extensão

Name Description
AsParallel(IEnumerable)

Permite a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable para um IQueryable.

Cast<TResult>(IEnumerable)

Conjura os elementos de an IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base num tipo especificado.

Aplica-se a

Segurança de Thread

Os membros estáticos públicos (Shared em Visual Basic) deste tipo são seguros para threads. Qualquer membro de instância não é garantido que seja seguro contra threads.

Esta implementação não fornece um wrapper sincronizado (seguro para threads) para um StringCollection, mas classes derivadas podem criar as suas próprias versões sincronizadas do StringCollection usando a SyncRoot propriedade.

Enumerar através de uma coleção não é intrinsecamente um procedimento seguro para threads. Mesmo quando uma coleção está sincronizada, outros threads ainda podem modificar a coleção, o que faz com que o enumerador lance uma exceção. Para garantir a segurança dos threads durante a enumeração, pode bloquear a coleção durante toda a enumeração ou apanhar as exceções resultantes de alterações feitas por outros threads.

Ver também