linq select a random row

后端 未结 6 1393
悲&欢浪女
悲&欢浪女 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:40

    1 First create a class with rend property

    public class tbl_EmpJobDetailsEntity
    {
        public int JpId { get; set; }
        public int rend
       {
        get
          {
            Random rnd = new Random();
            return rnd.Next(1, 100);
          }
        }
    }
    

    2 Linq query

    var rendomise = (from v in db.tbl_EmpJobDetails
    select new tbl_EmpJobDetailsEntity
    {
       JpId=v.JpId
    }).OrderBy(o=>o.rend);
    
    0 讨论(0)
  • 2020-12-30 03:45

    I did it something like this:

    list.ElementAt(rand.Next(list.Count());
    

    I stuck a bunch of random operations, including select and shuffle, as extension methods. This makes them available just like all the other collection extension methods.

    You can see my code in the article Extending LINQ with Random Operations.

    0 讨论(0)
  • 2020-12-30 03:48

    Here is one way to achieve what you want to do:

    var quotes = from q in dataContext.Quotes select q;
    int count = quotes.Count();
    int index = new Random().Next(count);
    var randomQuote = quotes.Skip(index).FirstOrDefault();
    
    0 讨论(0)
  • 2020-12-30 03:49

    try it:

    list.OrderBy(x => Guid.NewGuid()).Take(1).first();
    
    0 讨论(0)
  • 2020-12-30 03:50
    Random rand = new Random();
    int toSkip = rand.Next(0, context.Quotes.Count);
    
    context.Quotes.Skip(toSkip).Take(1).First();
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题