开发者

Randomize database table result with LINQ

开发者 https://www.devze.com 2022-12-16 17:00 出处:网络
from f in db.Table1 orderby Guid.NewGuid() select开发者_如何学Go f this doesn\'t seem to work. how can i randomize results?How about
from f in db.Table1
orderby Guid.NewGuid()
select开发者_如何学Go f

this doesn't seem to work. how can i randomize results?


How about

SELECT TOP 1 column FROM table ORDER BY NEWID and skip the linq :)

Or try this:

var t = (from row in db.Table1 order by table1.random()
         select row).FirstOrDefault();


Maybe something like this works (not tested):

 (from f in db.Table1 select new { f, r = Guid.NewGuid()}).OrderBy(x => x.r)


Randomize whole list

db.Table1.OrderBy(x => Guid.NewGuid())

Get single Random

db.Table1.OrderBy(x => Guid.NewGuid()).FirstOrDefault();


I like to write an extension method for this.

IEnumerable<T> Randomize(this IEnumerable<T> list)
{
    T[] result = list.ToArray();
    Random random = new Random();

    for(int i = result.Length; i > 0; i--)
    {
        result[i] = random.Next(i);
    }

    return (result);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消