Get a random row with LINQtoSQL

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

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

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-20 05:30

    Yes, generate a random number in the range of the table's count and Skip() that number, Take(1) then return the first element of the resulting sequence. Something like

    var R = new Random();
    var ToSkip = R.Next(0, ctx.Customers.Count);
    
    return ctx.Customers.Skip(ToSkip).Take(1).First();
    

    But it's a bit ugly. Is there an actual requirement that calls for getting a random row in a SQL table?

提交回复
热议问题