Reputation: 1177
I have an enum:
public enum PrivilegedAccounts
{
User = 1,
Service = 16,
Admin = 64,
Other = 1040,
Executive = 2048
}
and I wish to rand a value different than user. I know there's this rand (not sure it's true):
foo = (PrivilegedAccounts) (rand());
but how do I make it to rand any value except for "user"?
Thank you,
Upvotes: 1
Views: 87
Reputation: 390
1- First counting the number of Enum
2- Make random number between the counts
3- create list of Enum
4- return the index of Enum
Random rnd = new Random();
var myEnumMemberCount = Enum.GetNames(typeof(PrivilegedAccounts)).Length; // Step1
int count = rnd.Next(1, myEnumMemberCount); // creates a number between 1 and PrivilegedAccounts count //Step2 User is ignored
Array eVals = Enum.GetValues(typeof(PrivilegedAccounts)); //Step3
PrivilegedAccounts foo = (PrivilegedAccounts)eVals.GetValue(count); //Step4
Upvotes: 0
Reputation: 86
I hope this is what you are looking for.
public enum PrivilegedAccounts
{
User = 1,
Service = 16,
Admin = 64,
Other = 1040,
Executive = 2048
}
var values = Enum.GetValues(typeof(PrivilegedAccounts));
SomeEnum randomValue = (PrivilegedAccounts)values[Random.Range(1, values.Length)]; //Start from 1 instead of 0 to avoid User
Upvotes: 3
Reputation: 57210
You can create a method :
static PrivilegedAccounts GetRandPrivAccountExcluding(
PrivilegedAccounts excludedValue, Random rand)
{
var privAccounts = Enum.GetValues(typeof(PrivilegedAccounts))
.OfType<PrivilegedAccounts>()
.Where(x => x != excludedValue)
.ToList();
return privAccounts[rand.Next(privAccounts.Count)];
}
Example usage :
static void Main(string[] args)
{
Random rand = new Random();
var randPriviledge = GetRandPrivAccountExcluding(PrivilegedAccounts.User, rand);
}
Upvotes: 0
Reputation: 338
Try something like this :
Random random = new Random();
int range_min = 1;
int range_max = 3;
int randomNumber;
do
{
randomNumber = random.Next(range_min, range_max);
} while (randomNumber == (Int32)PrivilegedAccounts.User);
Upvotes: 0