在ASP.NET中使用LINQ排序依据随机ThreadSafe的 [英] Linq Orderby random ThreadSafe for use in ASP.NET

查看:90
本文介绍了在ASP.NET中使用LINQ排序依据随机ThreadSafe的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC Asp.net与夏普架构。

i'm using Asp.net MVC with Sharp Architecture.

我有这样的code:

return _repositoryKeyWord.FindAll(x => x.Category.Id == idCAtegory)
                .Take(50).ToList();

如何订购通过随机?
注:我不想订购50提取的项目,在此之前我想顺序,然后抽取50个项目

How can i order by random? Note: i don't want to order the 50 extracted items, i want order before and then extract 50 items.

thks

推荐答案

要高效地实现的一种方式是将列添加到您的数据随机填充了随机INT(为创建的每个记录)。

One way to achieve efficiently is to add a column to your data Shuffle that is populated with a random int (as each record is created).

访问表的查询就变成...

The query to access the table then becomes ...

Random random = new Random();
int seed = random.Next();
result = result.OrderBy(s => (~(s.Shuffle & seed)) & (s.Shuffle | seed)); // ^ seed);

此确实XOR操作在数据库中,订单由异或的结果。

This does an XOR operation in the database and orders by the results of that XOR.

优点: -


  1. 高效:SQL处理
    订货,无需取整

  2. 重复:(好
    测试) - 可以使用相同的随机
    种子以产生相同的随机
    为了

  3. 适用于大多数(所有?)Entity Framework的支持
    数据库

这是使用我的家庭自动化系统,随机播放列表的方法。它每天挑选一个新的种子,白天给人一种一致的顺序(可方便的暂停/恢复功能),但是在每个播放列表重新审视每一个新的一天。

This is the approach used by my home automation system to randomize playlists. It picks a new seed each day giving a consistent order during the day (allowing easy pause / resume capabilities) but a fresh look at each playlist each new day.

这篇关于在ASP.NET中使用LINQ排序依据随机ThreadSafe的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆