StringCollection Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Representa una colección de cadenas.
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
- Herencia
-
StringCollection
- Derivado
- Atributos
- Implementaciones
Ejemplos
En el ejemplo de código siguiente se muestran varias de las propiedades y 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:
'
Comentarios
StringCollection acepta null como un valor válido y permite elementos duplicados.
La comparación de cadenas distingue mayúsculas de minúsculas.
Se puede acceder a los elementos de esta colección mediante un índice entero. Los índices de esta colección se basan en cero.
Constructores
| Nombre | Description |
|---|---|
| StringCollection() |
Inicializa una nueva instancia de la clase StringCollection. |
Propiedades
| Nombre | Description |
|---|---|
| Count |
Obtiene el número de cadenas contenidas en .StringCollection |
| IsReadOnly |
Obtiene un valor que indica si el StringCollection es de solo lectura. |
| IsSynchronized |
Obtiene un valor que indica si el acceso a StringCollection está sincronizado (seguro para subprocesos). |
| Item[Int32] |
Obtiene o establece el elemento en el índice especificado. |
| SyncRoot |
Obtiene un objeto que se puede usar para sincronizar el acceso a la StringCollection. |
Métodos
| Nombre | Description |
|---|---|
| Add(String) |
Agrega una cadena al final de .StringCollection |
| AddRange(String[]) |
Copia los elementos de una matriz de cadenas al final de .StringCollection |
| Clear() |
Quita todas las cadenas de .StringCollection |
| Contains(String) |
Determina si la cadena especificada está en .StringCollection |
| CopyTo(String[], Int32) |
Copia los valores completos StringCollection en una matriz unidimensional de cadenas, empezando por el índice especificado de la matriz de destino. |
| Equals(Object) |
Determina si el objeto especificado es igual al objeto actual. (Heredado de Object) |
| GetEnumerator() |
Devuelve un StringEnumerator objeto que recorre en iteración .StringCollection |
| GetHashCode() |
Actúa como la función hash predeterminada. (Heredado de Object) |
| GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
| IndexOf(String) |
Busca la cadena especificada y devuelve el índice de base cero de la primera aparición dentro de StringCollection. |
| Insert(Int32, String) |
Inserta una cadena en en el StringCollection índice especificado. |
| MemberwiseClone() |
Crea una copia superficial del Objectactual. (Heredado de Object) |
| Remove(String) |
Quita la primera aparición de una cadena específica de .StringCollection |
| RemoveAt(Int32) |
Quita la cadena en el índice especificado de .StringCollection |
| ToString() |
Devuelve una cadena que representa el objeto actual. (Heredado de Object) |
Implementaciones de interfaz explícitas
| Nombre | Description |
|---|---|
| ICollection.CopyTo(Array, Int32) |
Copia todo en StringCollection una unidimensional Arraycompatible, empezando por el índice especificado de la matriz de destino. |
| IEnumerable.GetEnumerator() |
Devuelve un IEnumerator objeto que recorre en iteración .StringCollection |
| IList.Add(Object) |
Agrega un objeto al final de .StringCollection |
| IList.Contains(Object) |
Determina si un elemento está en .StringCollection |
| IList.IndexOf(Object) |
Busca el especificado Object y devuelve el índice de base cero de la primera aparición dentro de todo StringCollection. |
| IList.Insert(Int32, Object) |
Inserta un elemento en en el StringCollection índice especificado. |
| IList.IsFixedSize |
Obtiene un valor que indica si el StringCollection objeto tiene un tamaño fijo. |
| IList.IsReadOnly |
Obtiene un valor que indica si el StringCollection objeto es de solo lectura. |
| IList.Item[Int32] |
Obtiene o establece el elemento en el índice especificado. |
| IList.Remove(Object) |
Quita la primera aparición de un objeto específico de .StringCollection |
Métodos de extensión
| Nombre | Description |
|---|---|
| AsParallel(IEnumerable) |
Habilita la paralelización de una consulta. |
| AsQueryable(IEnumerable) |
Convierte un IEnumerable en un IQueryable. |
| Cast<TResult>(IEnumerable) |
Convierte los elementos de un IEnumerable al tipo especificado. |
| OfType<TResult>(IEnumerable) |
Filtra los elementos de un IEnumerable en función de un tipo especificado. |
Se aplica a
Seguridad para subprocesos
Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para subprocesos. No se garantiza que los miembros de instancia sean seguros para el acceso concurrente.
Esta implementación no proporciona un contenedor sincronizado (seguro para subprocesos) para una StringCollectionclase , pero las clases derivadas pueden crear sus propias versiones sincronizadas de StringCollection mediante la SyncRoot propiedad .
La enumeración a través de una colección no es intrínsecamente un procedimiento seguro para subprocesos. Incluso cuando se sincroniza una colección, otros subprocesos todavía pueden modificar la colección, lo que hace que el enumerador inicie una excepción. Para garantizar la seguridad de los subprocesos durante la enumeración, puede bloquear la colección durante toda la enumeración o detectar las excepciones resultantes de los cambios realizados por otros subprocesos.