A LINQ query is a recipe, not a result.

The problem
Two uses, two runs.
var alive = enemies.Where( e => e.Health > 0 ); int count = alive.Count(); // runs the filterforeach ( var e in alive ) // runs it again e.Think();
Where doesn't filter anything yet. Every use of alive runs the whole filter from the start.
Why it happens
Queries are lazy.
LINQ waits until you ask for results, then works them out fresh, every time.
- Where, Select, OrderBy
- build the recipe
- Count, foreach, ToList
- run it
- The list changes
- so do the results
The fix in code
Run it once with ToList.
var alive = enemies.Where( e => e.Health > 0 ).ToList(); int count = alive.Count; // just a numberforeach ( var e in alive ) e.Think();
ToList runs the query once and keeps the answer. Count is a property now, not a recount.
Watch out
Sometimes lazy is what you want.
A list is a snapshot. If you need the live answer later, keep the query.
- Used twice, right now
- ToList
- Need the live answer
- keep the query
- Every frame
- a plain loop
The rule
Using it twice? ToList it once.
- Builds the recipe
- Where, Select
- Runs it
- Count, foreach
- Run once, keep it
- ToList()