我编写了一个函数,可以从列表中获取给定数量的随机记录。目前我可以做类似的事情:
IEnumerable<City> cities = db.Cites.GetRandom(5);
(其中 db 是我连接到 SQL Server 数据库的 DataContext)
目前,我在每个需要随机记录的实体中都有这样的函数:
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>
.
我不明白这里的问题是什么。有人可以清除正确的语法吗?
最佳答案
我喜欢随机排序函数的想法,它可以像这样应用于任何 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);
关于c# - 自定义 Linq 扩展语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/351915/