Pregunta

Tengo List<sting> con 5 entradas.[0],[1],[2],[3],[4].

si utilizo List.Clear(), se eliminan todos los elementos.

Necesito eliminar hasta un artículo específico, por ejemplo, hasta [1].eso significa que en mi lista son solo 2 items [0] and [1].¿cómo hacer eso con c #?

¿Fue útil?

Solución

Puede usar List.RemoveWhere (Predicate) .. Alternativamente, puede hacer un bucle for - bucle hacia atrás, eliminando elementos hasta el elemento que busca, es decir

for(var i = List.Count()-1; i>=0; i--) {
   var item = List[i];
   if (item != "itemThatYourLookingFor") {
      List.Remove(item);
      continue;
   }
   break;
}

Otros consejos

Si desea eliminar todos los elementos después del índice 1 (es decir, conservar solo los dos primeros elementos):

if (yourList.Count > 2)
    yourList.RemoveRange(2, yourList.Count - 2);

Si necesita eliminar todos los elementos después del elemento con un valor de "[1]", independientemente de su índice:

int index = yourList.FindIndex(x => x == "[1]");
if (index >= 0)
    yourList.RemoveRange(index + 1, yourList.Count - index - 1);

Puede utilizar el método GetRange .

Entonces ...

myList= myList.GetRange (0,2);

.. le daría lo que está pidiendo arriba.

List<string> strings = new List<string>{"a", "b", "c", "d", "e"};
List<string> firstTwoStrings = strings.Take(2).ToList();
// firstTwoStrings  contains {"a", "b"}

El método Take(int count) le permitirá contar elementos.

Puede eliminar un rango de una lista, dando el inicioíndice y el número de elementos que se eliminarán.

var items = new List<string> {"0", "1", "2", "3", "4", "5"};
var index = items.IndexOf("1") + 1;

if (index >= 0)
{
    items.RemoveRange(index, items.Count - index);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top