Using LINQ to manage Lists and Arrays in C#

In development, we often need to look through arrays, lists and such, to perform some kind of operations. For instance, let us say that we want to loop through an array to check in any of the items matches a certain criteria.

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

Most developers have written a loop of this sort at some point. I recently discovered there is a simpler way to do this in C#, using LINQ.

using System.Linq;
 
Enemy[] enemies = GetEnemies();
 
if (enemies.Any(enemy => enemy.alive)) {
    // Do something
}

Much more easy to read and write, 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 methods that just need to run once, like constructors and such, probably.

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

Credit: ADAMGRYU