There is no built-in function that returns a random record from the database using LINQ to SQL. One way is to create a user-defined function in a partial class of the data context.
public partial class DataContextNameHere : System.Data.Linq.DataContext
{
//some code here
[Function(Name = "NEWID", IsComposable = true)]
public Guid Random()
{
throw new NotImplementedException();
}
public Guid Random()
{
throw new NotImplementedException();
}
}
To use this method in your LINQ Statement, here is an example for a small number of records:
DataContext DbContext = new DataContext();
var result = (from r in DbContext.TableName
orderby DbContext.Random()
select r).FirstOrDefault();
For a large number of records, multiple queries is advisable to use, where it get the number of records and pick one at random.
DataContext DbContext = new DataContext();
var list = from r in DbContext.TableName
select r;
int count = list.Count(); // get count here
int index = new Random().Next(count);
var result = list.Skip(index).FirstOrDefault(); // pick on here
L.





2 comments:
Good one
Thank you for the comment. Feel free to check the other posts. :)
Post a Comment