public IEnumerable <Entity> GetEntitiesInRectSorted(Vector2 topLeft, Vector2 bottomRight, bool partial) { List <Entity> entities = new List <Entity>(); foreach (Entity e in integrator.GetEntitiesInRect(topLeft, bottomRight, partial)) { e.CalculatedSortValue = Sort(e); int insertAt = 0; for (int i = entities.Count - 1; i >= 0; i--) { if (entities[i].CalculatedSortValue <= e.CalculatedSortValue) { insertAt = i + 1; break; } } entities.Insert(insertAt, e); } for (int i = 0; i < entities.Count; i++) { yield return(entities[i]); } }