I have written a function that gets a given number of random records from a list. Currently I can do something like:
IEnumerable<City> cities = db.Cites.GetRandom(5);
(where db is my DataContext connecting to a SQL Server DB)
Currently, I have a function like this in every entity I need random records from:
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;
}
}
It works fine, but I'd like it to be generic, so it can work for any table, or even any list of items. I have tried an extension method like:
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;
}
but I get:
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'
which higlights "GetRandom"
I don't understand what the problem is here. Can someone clear up the proper syntax?