Using LINQ to manage Lists and Arrays in C#

Looping through array, lists and such types of structures is a common practice in development. It requires the well-known loop code

Enemy[] enemies = GetEnemies();

bool anyEnemyAlive = false;
foreach (Enemy enemy in enemies) {
    if (enemy.alive) {
        anyEnemyAlive = true;
        break;
    }
}
if (anyEnemyAlive) {
    // Do something
}

I am sure most of you have written this loop about 1 million times. I recently discovered there is a simpler way to do this:

using System.Linq;

Enemy[] enemies = GetEnemies();

if (enemies.Any(enemy => enemy.alive)) {
    // Do something
}

Much more pleasant to the eye, right?

But this approach should be use with care, since it can have unexpected performance hits or garbage allocations. It would be best used for one-time set up methods, probably.

Feel free to comment on this technique and share your thoughts.

Credit: ADAMGRYU

Leave a Reply

Your email address will not be published. Required fields are marked *