Reputation: 45
I have a list that contains names of Unity gameobjects.
I would like to have a method that I can call with the one of the names in the list, and it to return how many of that name is in the list.
How could I make this?
Upvotes: 2
Views: 3228
Reputation: 236
Let's say you have a List called namesList, you can make a for-loop and check for each item if it exists inside this list and count how many time you found it.
public int countNameOccurance(string name, List<string> namesList) {
int count = 0;
for(int i=0; i < namesList.Count(); i++){
if( namesList[i] == name){//check if the item exists in the list
count++;
}
}
return count;
}
Upvotes: 1
Reputation: 17027
With Linq its ultra easy:
suppose you have a List of string named list and search for Name, so you could write:
using System.Linq;
:
private int Count(List<string> list, string NameSearch)
{
return list.Count(n => n == NameSearch);
}
Upvotes: 3