Get a random row with LINQtoSQL

后端 未结 6 1566
忘掉有多难
忘掉有多难 2021-01-20 04:39

Is there a way to return a random row from a table using LINQToSQL?

6条回答
  •  [愿得一人]
    2021-01-20 05:40

    I'd try something like:

    query.Skip(rand.Next()).Take(1).FirstOrDefault();
    

    With rand being initialised as returning a number between a specific range.

    Be sure to check for null as the return value in case the random number generated was greater than the number of rows (of course you could initialise it's upper bound as the number of rows, too).

提交回复
热议问题