> For the complete documentation index, see [llms.txt](https://csharp.progdocs.se/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://csharp.progdocs.se/tekniker-och-designmonster/ta-bort-saker-ur-listan-man-gar-igenom.md).

# Ta bort saker ur listan man går igenom

## Problemet

Om man har en lista och använder for eller foreach för att gå igenom den, så blir det väldigt fel om man tar bort saker ur listan medan man loopar genom den.

```csharp
List<int> numbers = new List<int>() {1,2,3,4,5,6};

foreach (int n in numbers)
{
  if (n < 4)
  {
    numbers.Remove(n); // Ger runtime-felmeddelande
  }
}
```

## En traditionell lösning

Den här lösningen innebär att man helt enkelt lägger in alla saker som ska tas bort ur listan in i en ny, separat lista. Sedan går man igenom *den* listan, men tar bort sakerna ur den *ursprungliga* listan.

```csharp
List<int> numbers = new List<int>() {1,2,3,4,5,6};

List<int>numbersToRemove = new List<int>();

foreach (int n in numbers)
{
  if (n < 4)
  {
    numbersToRemove.Add(n);
  }
}

foreach(int n in numbersToRemove)
{
  numbers.Remove(n);
}

numbersToRemove.Clear();
```

## Lambda

RemoveAll()-metoden i List-klassen ger oss ett enklare sätt att lösa saken på ­med ett [Lambda-uttryck](/grundlaggande/delegates.md#lambdas):

```csharp
List<int> numbers = new List<int>() {1,2,3,4,5,6};

numbers.RemoveAll(n => n < 4);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://csharp.progdocs.se/tekniker-och-designmonster/ta-bort-saker-ur-listan-man-gar-igenom.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
