Random row from Linq to Sql

前端 未结 15 2532
南笙
南笙 2020-11-22 05:39

What is the best (and fastest) way to retrieve a random row using Linq to SQL when I have a condition, e.g. some field must be true?

15条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 05:53

    One way to achieve efficiently is to add a column to your data Shuffle that is populated with a random int (as each record is created).

    The partial query to access the table in random order is ...

    Random random = new Random();
    int seed = random.Next();
    result = result.OrderBy(s => (~(s.Shuffle & seed)) & (s.Shuffle | seed)); // ^ seed);
    

    This does an XOR operation in the database and orders by the results of that XOR.

    Advantages:-

    1. Efficient: SQL handles the ordering, no need to fetch the whole table
    2. Repeatable: (good for testing) - can use the same random seed to generate the same random order

    This is the approach used by my home automation system to randomize playlists. It picks a new seed each day giving a consistent order during the day (allowing easy pause / resume capabilities) but a fresh look at each playlist each new day.

提交回复
热议问题