How to shuffle a list of objects through a default value?

Asked

Viewed 119 times

2

I have the following object:

public class Object{
    public String ID{get;set;}
}

And in a moment in my code I get a list of them:

List<Object> objs = new List<Object>();
objs.add(new Object{ID = "1"});
objs.add(new Object{ID = "2"});
objs.add(new Object{ID = "3"});
objs.add(new Object{ID = "4"});

And then I randomize the objects:

objs = objs.OrderBy(a => Guid.NewGuid()).ToList();
Debug.WriteLine(objs.ID);
// 1 4 2 3

If I run objs.OrderBy(a => Guid.NewGuid()).ToList(); I’ll get a totally random order // 3 2 4 1.

I need to pass a "Seed" (an integer) and randomize relative to it, for example, if I pass the number 1 and receive // 3 2 4 1, when I run number 1 again I need to receive the same order.

Is there a resource in c# to do this?

2 answers

2

Instead of using GUID within the method Enumerable.OrderBy use the method Random.Next(int maxValue) of an object Random instantiated by the constructor Random(int seed), so generating the same sequence of pseudo-random numbers every Seed.

Example:

var rand = new Random(4);
var ListaEmbaralhada = Lista.OrderBy(a => rand.Next(Lista.Count)).ToList();

1

There is. The Random accepts this Seed you were talking about. If you always start with the same value it will always produce the same sequence.

var r = new Random(4);
var list = new List<int>(){1, 2, 3, 4, 5};
for(int i = 0; i < list.Count; ++i){
    var idx = r.Next(list.Count);
    var aux = list[idx];
    list[idx] = list[i];
    list[i] = aux;
}
list.Dump();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.