How to Use List.Contains() and random int

Hi there,
I have a list, which I am adding to during the running of a for(). As i go thru this for loop, I want to check the list to see if any value, int, already exists. I believe I need to use the Contains() but I can not figure out how to apply it to my circumstance.

		for(int i = 0; i < nmbrFE; i++){
			rdnmInt = Random.Range(0, dbInGroup.Length);
			///NOW, before I add this rdmInt to the list, 
			//....I must see if it already exists in the list. ???
			
			///if(rdmInt does not exist already in list… add)
			groupMembersUsedLsit.Add(rdmInt);
		}

Not really a Unity question but - Contains returns a bool, so check if Contains is false and if so add to the list. Alternately, depending on your use case, use a HashSet.

Just use something like:

if (!groupMembersUsedLsit.Contains(rdnmInt))
    groupMembersUsedLsit.Add(rdmInt);

Thank you. I got it right after I posted.
D’oh!

Cheers.
:slight_smile:

I don’t think you want a List. If the items are distinct, use a HashSet.

What would the difference be?
The purpose of my function is to never have a repeating int.

Generate random int.
Has random int already been created?
No. Put in list.
Yes. Re run loop.

Well, the hash set is going to be faster in terms of finding unique keys. Generally speaking.

Basically a list and hash set are the same no? What are the big differences? Advantages in various situations?

A HashSet guarantees that all values are unique. And it’s also faster than List.Contains

Honestly? If you’re serious about doing development work then it really pays to do some research yourself.

Easy on the motion, while the thread seems hot, it is good to ask.

So, with a HashSet I can not duplicate any value? That would be one difference.

It took me less time to search for and then go to this page than I’m sure it did for you to type your post.

http://msdn.microsoft.com/en-us/library/bb359438(v=vs.90).aspx

Thumbs up.