从Linq到Sql的随机行

从Linq到Sql的随机行,第1张

从Linq到Sql的随机行

您可以通过使用伪造的UDF在数据库上执行此 *** 作;在部分类中,向数据上下文添加一个方法

partial class MyDataContext {     [Function(Name="NEWID", IsComposable=true)]      public Guid Random()      { // to prove not used by our C# pre...          throw new NotImplementedException();      }}

然后就

order by ctx.Random()
; 这将根据进行SQL Server的随机排序
NEWID()
。即

var cust = (from row in ctx.Customerswhere row.IsActive // your filterorderby ctx.Random()select row).FirstOrDefault();

请注意,这仅适用于中小型表;对于大型表,这将对服务器的性能产生影响,找到行数(

Count
),然后随机选择一个(),效率会更高
Skip/First


对于计数方法:

var qry = from row in ctx.Customers          where row.IsActive          select row;int count = qry.Count(); // 1st round-tripint index = new Random().Next(count);Customer cust = qry.Skip(index).FirstOrDefault(); // 2nd round-trip


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5559886.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存