2008-12-09 106 views
2

我写了一个函数,它可以从列表中获取给定数量的随机记录。目前,我可以这样做:自定义Linq扩展语法

IEnumerable<City> cities = db.Cites.GetRandom(5); 

(其中db是我的DataContext连接到SQL Server DB)

目前,我在每一个实体这样的功能,我需要随机记录来自:

public partial class City 
{ 

    public static IEnumerable<City> GetRandom(int count) 
    { 
     Random random = new Random(); 
     IEnumerable<City> cities = DB.Context.Cities.OrderBy(c => random.Next()).Take(count); 

     return cities; 
    } 

} 

它工作正常,但我希望它是通用的,所以它可以适用于任何表,甚至任何项目列表。我试图像一个扩展方法:

public static IEnumerable<T> GetRandom<T>(this Table<T> table, int count) 
    { 
     Random random = new Random(); 
     IEnumerable<T> records = table.OrderBy(r => random.Next()).Take(count); 

     return records; 
    } 

,但我得到:

 
    Error 1 The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Linq.Table' 

这凸显GetRandom<T>

我不明白这里的问题是什么。有人可以清理正确的语法吗?

+0

要修复您的GetRandom方法,请在该方法的参数后面添加'where T:class'。 – 2009-04-10 16:34:12

回答

4

JaredPar,我不认为你可以做到这一点与:类通用定义中。

我觉得这是定义的类型约束的正确方法:

public static IEnumerable<T> GetRandom<T>(this Table<T> table, int count) where T : class { 
    ... 
} 

更多类型约束信息here

+0

你是对的,我正在用不同的语言进行约束:( – JaredPar 2008-12-09 06:28:49

0

试试这个

public static IEnumerable<T> GetRandom<T>(this Table<T> table, int count) where T : class { 
    ... 
} 
6

我喜欢随机顺序功能的想法,它可以应用到任何IEnumerable的像这样:

public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source) 
{ 
    Random rnd = new Random(); 
    return source.OrderBy(t => rnd.Next()); 
} 

... 

IEnumerable<City> cities = db.Cites.Randomize().Take(5); 
5

如果你在谈论到数据库,你可能想要做在随机取数据库。

 [Function(Name="NEWID", IsComposable=true)] 
    public Guid Random() 
    { 
     return Guid.NewGuid(); 
    } 

然后通过在一个查询:

 ctx.Log = Console.Out; 
    var query = from x in ctx.Suppliers 
       orderby ctx.Random() 
       select x; 
    var results = query.ToArray(); 
与LINQ到SQL您可以(为短小的体积)通过[功能]在NEWID指向(上的数据上下文)做到这一点

这给TSQL(这里使用罗斯文):

SELECT [t0].[SupplierID], [t0].[CompanyName], [t0].[ContactName], 
[t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], 
[t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax], [t0].[HomePage] 
FROM [dbo].[Suppliers] AS [t0] 
ORDER BY NEWID() 

可以很明显的与采取这种混合(1)等

它不尽管在实体框架中工作。