How to search for corresponding items in List?

This is my class:

public class EnemyInfo
	public GameObject enemy;
	public int threatLevel;

	public EnemyInfo(GameObject Enemy, int ThreatLevel)
		enemy = Enemy;
		threatLevel = ThreatLevel;

I setup 2 variables:

GameObject target;
public List<EnemyInfo> enemyList = new List<EnemyInfo>();

Lets say I set a target:

target = enemyList[0].enemy;

How can I find the corresponding “threatLevel” value to target without explicitly calling it, like below:


Instead, I am trying to search through my list for the gameobject that matches “target” and retrieve the corresponding threatLevel value? I am stuck with the syntax. Is a for statement required or is there a quicker way find it?

Any help appreciated, thanks.

The List class has a build in Find function. For your example, you could use it in the following way:

EnemyInfo enemyInList = enemyList.Find( x => x.enemy==target);

This will find the first occurrence of the target in the list. If your list can contain duplicates of the same object, List also has a FindAll function.