用于 ASP.NET 的 Linq Orderby 随机 ThreadSafe [英] Linq Orderby random ThreadSafe for use in ASP.NET

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

问题描述

我正在使用具有 Sharp 架构的 Asp.net MVC.

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

我有这个代码:

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.

谢谢

推荐答案

一种有效实现的方法是向数据 Shuffle 添加一列,该列填充有随机整数(因为每条记录都是创建).

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 操作并根据 XOR 的结果进行排序.

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

优点:-

  1. 高效:SQL 处理订购,无需取整表
  2. 可重复:(适合测试) - 可以使用相同的随机种子生成相同的随机数订购
  3. 适用于大多数(全部?)实体框架支持数据库

这是我的家庭自动化系统用来随机播放列表的方法.它每天选择一个新的种子,在白天给出一致的顺序(允许轻松暂停/恢复功能),但每天都会重新审视每个播放列表.

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 Orderby 随机 ThreadSafe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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