0

I am very new to C# programing, i know other languages (high level) but i dont know how i could do this. I want to make a list [] that contains random set order numbers but it will only create numbers from another list e.g NumberLis = [0,1]

NumberList = [0,1]
list =  [NumberList(random(0,1))]

i know how to do this in python, Python code for what im trying to do (if that helps) import random

NumberList = [0,1] #The set numbers
List = []
for i in range(10):
    List.append(NumberList[random.randint(0,1)])
print(List)
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Do you want to create a collection in which the values are pulled from another set in random order or take a random subset from the first collection? – tvanfosson Jun 07 '15 at 02:14

3 Answers3

0

I would go about doing it this way:

int[] source = new [] { 0, 1, };

var rnd = new Random();

List<int> result =
    Enumerable
        .Range(0, 100)
        .Select(n => source[rnd.Next(0, source.Length)])
        .ToList();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0

To select a fixed number of items from a collection randomly (with repeats) you only need to select the index into the population randomly, then add the randomly selected item to your result set. If you don't want repeats, then I would suggest using a shuffle. A very good answer on how to implement a shuffle algorithm can be found to this question Is using Random and OrderBy a good shuffle algorithm?

Example with repeats.

var populationSize = 1000;
var population = Enumerable.Range(0, populationSize); // example - your population could be different

var randomSet = new List<int>();
var setSize = 10;

var random = new Random();

for (var i = 0; i < setSize; ++i)
{
    var idx = random.Next(populationSize);
    randomSet.Add(population[idx]);
}

Or using LINQ

var setSize = 10;
var random = new Random();
var randomSet = Enumerable.Range(0, setSize)
                          .Select(i => population[random.Next(populationSize)]);
Community
  • 1
  • 1
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
-1

A little linq. Code below will take any input list.

Random rand = new Random();
List<int> input = new List<int>() { 1, 54, 4, 3, 7, 8 };
List<int> output = input.Select(x => new {rand = rand.Next(), value = x}).OrderBy(y => y.rand).Select(z => z.value).ToList();​
John Saunders
  • 160,644
  • 26
  • 247
  • 397
jdweng
  • 33,250
  • 2
  • 15
  • 20