Random row from Linq to Sql

前端 未结 15 2327
南笙
南笙 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 06:13

    if you want to get e.g. var count = 16 random rows from table, you can write

    var rows = Table.OrderBy(t => Guid.NewGuid())
                            .Take(count);
    

    here I used E.F, and the Table is a Dbset

    0 讨论(0)
  • 2020-11-22 06:15
    List<string> lst = new List<string>();
    lst.Add("Apple"); 
    lst.Add("Guva");
    lst.Add("Graps"); 
    lst.Add("PineApple");
    lst.Add("Orange"); 
    lst.Add("Mango");
    
    var customers = lst.OrderBy(c => Guid.NewGuid()).FirstOrDefault();
    

    Explanation: By inserting the guid (which is random) the order with orderby would be random.

    0 讨论(0)
  • 2020-11-22 06:15

    The example below will call the source to retrieve a count and then apply a skip expression on the source with a number between 0 and n. The second method will apply order by using the random object (which will order everything in memory) and select the number passed into the method call.

    public static class IEnumerable
    {
        static Random rng = new Random((int)DateTime.Now.Ticks);
    
        public static T RandomElement<T>(this IEnumerable<T> source)
        {
            T current = default(T);
            int c = source.Count();
            int r = rng.Next(c);
            current = source.Skip(r).First();
            return current;
        }
    
        public static IEnumerable<T> RandomElements<T>(this IEnumerable<T> source, int number)
        {
            return source.OrderBy(r => rng.Next()).Take(number);
        }
    }
    
    0 讨论(0)
提交回复
热议问题