Reputation: 177
I have the object:
public class Object{
public String ID{get;set;}
}
And my software receive a List:
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 it:
objs = objs.OrderBy(a => Guid.NewGuid()).ToList();
Debug.WriteLine(objs.ID);
// 1 4 2 3
If I execute objs.OrderBy(a => Guid.NewGuid()).ToList();
i'm going to receive another random sequence // 3 2 4 1
.
I need to pass a "seed"(a integer number) and randomize about this number, for example, if I pass the seed 1
I receive // 3 2 4 1
, when I execute the number 1 again i need to receive the same order // 3 2 4 1
.
There is a way to do it in c#?
Edit: The object above is just a example, the real case i need to randomize the following object:
public class Object{
public Int ID{get;set;}
public String ImageTitle{get;set;}
public String ImageDescription{get;set;}
public String Url {get;set;}
}
Upvotes: 0
Views: 203
Reputation: 449
Use this method and cache randomized arrays and serve it again. easy.
private Dictionary<int, List<Object>> randoms=new Dictionary<int, List<Object>>();
private List<Object> GetRandom(List<Object> objs,int? seed)
{
if (seed == null)
{
return objs.OrderBy(a => Guid.NewGuid()).ToList();
}
else
{
if (!randoms.ContainsKey(seed.Value))
randoms[seed.Value] = objs.OrderBy(a => Guid.NewGuid()).ToList();
return randoms[seed.Value];
}
}
Example call GetRandom(objs,null) will always randomize it. If you call it with number GetRandom(objs,1) he will serve old randomized array.
Upvotes: 0
Reputation: 82474
Not with GUID
, but with Random
it's not only possible but easy:
var seed = 123;
var r = new Random(seed);
objs = objs.OrderBy(o => r.Next()).ToList();
You can see a live demo on rextester.
Upvotes: 3