Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a free entry in a C# dictionary

Tags:

c#

dictionary

I am running a server, and I would like to have a users dictionary, and give each user a specific number.

Dictionary<int,ServerSideUser> users = new Dictionary<int,ServerSideUser>();

The key represents the user on the server, so when people send messages to that user, they send them to this number. I might as well have used the users IP number, but that's not that a good idea.

I need to allocate such a number for each user, and I'm really not sure how to do so. Someone suggested something like

Enumerable.Range(int.MinValue, int.MaxValue)
.Except(users.Select(x => x.Key)).First();

but I really don't think it's the optimal way. Also, I have the same problem with a List (or LinkedList) somewhere else.

Any ideas?

like image 641
Nefzen Avatar asked Dec 28 '25 00:12

Nefzen


1 Answers

If the size of the "number" doesn't matter, take a Guid, it will always be unique and non-guessable.

like image 142
Lucero Avatar answered Dec 30 '25 16:12

Lucero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!