tenthplanet0 - 3 months ago 56

C# Question

In C#, how do I get a random number from a range of values - like 1..100, but that number should not be in some specific list of values, like 5, 7, 17, 23?

Answer

Since no-one has posted any example code:

```
private int GiveMeANumber()
{
var exclude = new HashSet<int>() { 5, 7, 17, 23 };
var range = Enumerable.Range(1, 100).Where(i => !exclude.Contains(i));
var rand = new System.Random();
int index = rand.Next(0, 100 - exclude.Count);
return range.ElementAt(index);
}
```

Here's the thinking:

- Build a Hashset of numbers you want to exclude
- Create a collection of all the numbers 0-100 which aren't in your list of numbers to exclude with a bit of LINQ.
- Create a random object.
- Use the Random object to give you a number between 0 and the number of elements in your range of numbers (inclusive).
- Return the number at that index.