-1

I have an IQueryable<Post> and to sort it randomly I do the following:

IQueryable<Post> posts = getPosts();

posts = posts.OrderBy(x => Guid.NewGuid());

Is it possible to sort it randomly but for each day?

If I order it on 18 of April I would always get the same order.

But on 19 of April I would get another random order.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Does collection of Post change during the day? How about cache with expiry time based on date? You would order them only once a day and you would use cached order throughout whole day and the reorder the next day? – S. Kalinowski Apr 18 '20 at 23:40
  • Does this answer your question? [Randomize a List](https://stackoverflow.com/questions/273313/randomize-a-listt) – Pavel Anikhouski Apr 19 '20 at 09:49
  • @PavelAnikhouski - Why would that answer this question? – Enigmativity Apr 19 '20 at 09:56
  • @Enigmativity because it explains how to use `Random` class, `Guid.NewGuid` and other techniques to solve OP question, as well as a lot of duplicates on this site – Pavel Anikhouski Apr 19 '20 at 10:06
  • @PavelAnikhouski - But that's not what the OP is asking. He wants a stable sort for each day. He clearly knows how to sort randomly (albeit he's using a Guid which isn't the best way to get randomness). – Enigmativity Apr 19 '20 at 10:42

1 Answers1

4

Guids are not guaranteed to be random, only unique. Do not use Guids for random data. There are specific classes in the .NET framework designed to give (pseudo) random numbers - Random is the easiest one, but if you want crypographical quality try System.Security.Cryptography.RandomNumberGenerator.

In your case Random is your friend. You can seed it with a value created from today's date.

Try this:

var seed = (int)DateTime.Now.Date.Ticks;
var random = new Random(seed);

IQueryable<Post> posts = getPosts();

Post[] sorted =
    posts
        .ToArray()
        .Select(post => new { post, random = random.Next() })
        .OrderBy(x => x.random)
        .Select(x => x.post)
        .ToArray();

When I run that with the harness code:

IQueryable<Post> getPosts()
{
    return Enumerable.Range(0, 5).Select(x => new Post() { Id = x }).AsQueryable();
}

public class Post
{
    public int Id;  
}

I get 4, 3, 1, 0, 2 today. Tomorrow it will be 4, 2, 3, 0, 1. And Tuesday it will be 3, 4, 2, 0, 1.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • This is a good answer - just some notes here for people not familiar with `Random`, the class implements pseudo random number generating, that, for same seed value, `Next` returns same result. – weichch Apr 19 '20 at 21:15