How do I get a random number from numbers available?

Viewed 148

I have a table that I am trying to get a random number from:

//Fruits
id  |  FruitName
----------------
2   |  Banana
3   |  Apple
4   |  Orange
6   |  Grape
7   |  Plum
8   |  Lime
10  |  Kiwi

The problem is because of the inconsistencies (note: ids 1, 5, and 9 are missing), writing the following statement will not work (even if written properly):

Random.Next(someLinq.id).First(), (samelinq.id).Last())

How would I get a random number from the numbers available?

4 Answers

You can simply use the count of the items as the max random number, and then select a random item by index:

var random = new Random();
var items = new List<int> {2, 3, 4, 6, 7, 8, 10};
var randomItem = items[random.Next(items.Count)];

Or, in your case (and assuming you are getting a list of Fruit items which contain an Id property):

var items = new List<Fruit>
{
    new Fruit {Id = 2, Name = "Banana"},
    new Fruit {Id = 3, Name = "Apple"},
    new Fruit {Id = 4, Name = "Orange"},
    new Fruit {Id = 6, Name = "Grape"},
    new Fruit {Id = 7, Name = "Plum"},
    new Fruit {Id = 8, Name = "Lime"},
    new Fruit {Id = 10, Name = "Kiwi"}
};

var random = new Random();
var randomItem = items[random.Next(items.Count)];

Console.WriteLine("Randomly chose fruit: Id = {0}, Name = {1}", 
    randomItem.Id, randomItem.Name);

you can add all numbers in a array after you can create a random with array's lengt and you can use this number as index of number in the array

int[] array = new int[]{2,3,4,6,7,8,10};
Random rnd = new Random();
int randomIndex = rnd.Next(0,array.length);
var x = array[randomIndex];

And you can do what you want with this x variable

How about something like this?

// get the count
var count = context.Fruits.Count();
// generate a random fruit index
var random = new Random().Next(count);
// skip by random
var randomFruit = context.Fruits
                         .Skip(random)
                         .Take(1)
                         .FirstOrDefault();

For a statitstical and cryptographically absolutely not correct random value you could go with

var randomId = resultOfDbLinqQuery
    .OrderBy(e => Guid.NewGuid())
    .First()
    .Select(item = item.id);
Related