随机行从Sql的Linq [英] Random row from Linq to Sql

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

问题描述

什么是使用LINQ to SQL时,我有一个条件,例如中检索随机行的最佳,最快的方法有些字段必须是真实的?

What is the best (and fastest) way to retreive a random row using Linq to SQL when I have a condition, e.g. some field must be true ?

推荐答案

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

You can do this at the database, by using a fake UDF; in a partial class, add a method to the data context:

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

然后,只需按ctx.Random()秩序;这将会做的SQL服务器礼貌随机排序NEWID()。即。

var cust = (from row in ctx.Customers
           where row.IsActive // your filter
           orderby ctx.Random()
           select row).FirstOrDefault();

请注意,这仅适用于小到中等规模的表;巨额的表,它会在服务器性能的影响,这将是更有效地找到行数(计数),然后随机选择一个(跳过/第一)。

Note that this is only suitable for small-to-mid-size tables; for huge tables, it will have a performance impact at the server, and it will be more efficient to find the number of rows (Count), then pick one at random (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

这篇关于随机行从Sql的Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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