Avatar ·

How to remove elements from a List<T> using LINQ in C#?

Hello everyone! I'm a beginner in C# and encountered a situation where I need to remove several elements from a List that satisfy a certain condition. Currently, I'm using a regular for loop with removal by index, but it works incorrectly — after removal, the indices shift, and I skip elements.\n\nHere's an example: I have a list of numbers, and I want to remove all even numbers.\n\n```csharp\nList numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n\nfor (int i = 0; i < numbers.Count; i++)\n{\n if (numbers[i] % 2 == 0)\n {\n numbers.RemoveAt(i);\n }\n}\n```\n\nAfter this code, the list contains elements: 1, 3, 5, 7, 9 — which seems correct. But if I add more elements or complicate the condition, problems start. For example, if I remove an element at index 1 (value 2),