linq select a random row

后端 未结 6 1418
悲&欢浪女
悲&欢浪女 2020-12-30 03:05

I have a table called Quotes in linq-to-sql that contains 2 columns: author and quote. How do you select both columns of a random row?

6条回答
  •  旧巷少年郎
    2020-12-30 03:52

    If you're doing Linq-to-Objects and don't need this to work on SQL, you can use ElementAt() instead of the more verbose Skip(toSkip).Take(1).First() :

    var rndGen = new Random(); // do this only once in your app/class/IoC container
    int random = rndGen.Next(0, context.Quotes.Count);
    context.Quotes.ElementAt(random);
    

提交回复
热议问题