当我有条件时,使用 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/