How to check if all or half of list members are in certain condition

Example 1

if all(enemy.dead for enemy in enemyGroup):

Example 2

if sum(enemy.dead for enemy in enemyGroup) >= len(enemyGroup) * 0.5:

These two examples are from Python. enemyGroup is a list that contains all enemies. First example is checking if all enemies in enemyGroup list is dead, while the second example is checking if half of enemies in the list are dead.

I can’t figure out if I can or not, write a similar code in C# when manipulating with list. Is there a fancy way to translate this Python code to Unity in C#? If not, what is the most optimal way to check if all or half of members in the list meet certain condition?

Hi, you could create a foreach loop to check all members of your list like:

int deadCounter = 0;
foreach (GameObject enemy in enemyGroup)
if (enemy.dead == true)
deadCounter += 1;

if (deadCounter == enemyGroup.count)
//all enemies are dead
else if (deadCounter >= enemyGroup.count / 2)
//half or more of the enemies are dead

You can use Linq for such thing. Add this line at the top

using System.Linq;

Now you can do things like that:

List<YourClass> list;

int deadCount = list.Where(a=>a.dead).Count();
if(deadCount >= list.Count/2)

// ...

if (list.All(a=>a.dead))

Note you can even convert the items in place. However some linq methods may be quite expensive. The IEnumerable the linq methods create require some memory. You shouldn’t use them every frame.

List<GameObject> someGOs;

float sum = someGOs.Select(a=>a.GetComponent<YourScript>()).Where(a=>a.someVariable > 5).Sum(a=>a.fooBar);

This last example is equivalent to:

List<GameObject> someGOs;
float sum = 0;
foreach(var go in someGOs)
    YourScript s = og.GetComponent<YourScript>();
    if (s.someVariable > 5)
        sum += s.fooBar;