c# - 从 Linq 到 Sql 的随机行

标签 c# .net linq-to-sql

当我有条件时,使用 Linq to SQL 检索随机行的最佳(和最快)方法是什么,例如某些字段必须为真?

最佳答案

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

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

然后只需按 ctx.Random() 排序;这将在 NEWID() 的 SQL-Server 中进行随机排序。即

var cust = (from row in ctx.Customers
           where row.IsActive // your filter
           orderby 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-trip
int index = new Random().Next(count);

Customer cust = qry.Skip(index).FirstOrDefault(); // 2nd round-trip

关于c# - 从 Linq 到 Sql 的随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/648196/

相关文章:

c# - 正则表达式问题,将数据提取到组

c# - DataGrid 进行不需要的重新排列

c# - String.Contains 和 String.LastIndexOf C# 返回不同的结果?

c# - Asp.net core默认路由

c# - 按页复制文档以在使用 iTextsharp 之间插入空白页

c# - WPF 应用程序中的 LINQ TO SQL 生成连接是关闭异常,有时

winforms - 通过 Web 服务发送 Linq to SQL 类

.net - DataContext 范围最佳实践

c# - C#中使用大括号释放内存

c# - Stimulsoft,未找到程序集 'Stimulsoft.Report.Wpf',