- Home /
This question was
closed May 07, 2018 at 08:06 AM by
Myth for the following reason:
The question is answered, right answer was accepted
Find index of item in list
The purpose of the following code is to create a list of indexes of ammo that matches the requirements of a given weapon (type and caliber and effect)
In the following code, I get require a predicate to get it to work. (at the find index method)
How is this done/ is there a better method?
the code:
/// <summary>
/// Returns ammo matching the given type and prefix
/// </summary>
/// <returns>ammo matching the given type in a list</returns>
/// <param name="theAmmoType">The ammo type enum.</param>
public List<int> FetchAmmo (ammoType theAmmoType, string ammoPrefix)
{
// list to return
List<int> result = new List<int>();
// iterate through whitelisted ammo
foreach (var item in availableAmmo)
{
// sort
if (item.myAmmoType == theAmmoType)
{
// check prefix of string
if (item.name.Contains(ammoPrefix))
// add the item
result.Add(availableAmmo.FindIndex(item));
}
}
// throw back
return result;
}
Comment
Best Answer
Answer by fafase · Jun 10, 2015 at 06:24 AM
You are looking for the index of the item so use IndexOf with the item instead:
result.Add(availableAmmo.IndexOf(item));
if availableAmmo is an array
result.Add(Array.IndexOf(availableAmmo, item));
or use a for loop:
for (int i = 0; i < availableAmmo.Length ; i++) // or count if it is a list
{
if(condition){
result.Add(i);
}
}
Available ammo is a list as contains a variable amount of different ammo - or it was easier to setup