Linq to Entities, random order
The simple solution would be creating an array (or a List<T>
) and than randomize its indexes.
EDIT:
static IEnumerable<T> Randomize<T>(this IEnumerable<T> source) {
var array = source.ToArray();
// randomize indexes (several approaches are possible)
return array;
}
EDIT: Personally, I find the answer of Jon Skeet is more elegant:
var results = from ... in ... where ... orderby Guid.NewGuid() select ...
And sure, you can take a random number generator instead of Guid.NewGuid()
.
linq: order by random
http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx
return (from examQ in idb.Exam_Question_Int_Tbl
where examQ.Exam_Tbl_ID==exam_id
select examQ).OrderBy(x => Guid.NewGuid()).Take(50);
If this is LINQ-to-SQL you could simply add a ORDER BY NEWID()
to your SELECT statement.
As commented it might be better to use an algorithm like Fisher-Yates Shuffle, here is an implementation: https://stackoverflow.com/a/375446/284240
EF Code First: How to get random rows
Just call:
something.OrderBy(r => Guid.NewGuid()).Take(5)
Random sort list with LINQ and Entity Framework
You can't use a Random object in the query like that, as the object exists in your VB code, not in the database.
Get the result into a list first, then scramble it. It's much more efficient to use a scrambling algorithm like Fischer-Yates/Knuth than sorting on a random value:
Dim rnd as New Random()
For i As Integer = gardens.Count To 2 Step -1
Dim pos As Integer = rnd.Next(i)
Dim x = gardens(i - 1)
gardens(i - 1) = gardens(pos)
gardens(pos) = x
Next
Also, to sort on a random value you either have to know that the sorting algorithm won't ever reevaluate the relation between two given items, or you have to assign a random value to each item so that it uses the same value throughout the sorting. If the method that you tried would have been possible, you could have gotten the same bad result as for the browser choise page.
Randomize entity framework query results
this turned out to be very simple using extension methods, ordering by name first, then calling Take (top on T-sql) and randomizing later
context.Categories().OrderByName().Take(20).OrderByRandom();
public static IQueryable<Category> OrderByName(this IQueryable<Category> query)
{
return from c in query
orderby c.Name
select c;
}
public static IQueryable<T> OrderByRandom<T>(this IQueryable<T> query)
{
return (from q in query
orderby Guid.NewGuid()
select q);
}
Linq order by random without GUID
If you want to return results in random order, but that order will be the same if you are sending same string from client, then you can use Random
class to get pseudo-random order. This random generator can accept seed - a value, which is used to calculate starting value of pseudo-random sequence. Thus you are passing string
you can use it's hash code to get integer value for seed:
var seed = randomstring.GetHashCode();
var random = new Random(seed);
var channels = db.Channels
.Where(x => (id == 0) || (x.CategoryId == id))
.Where(q => word == "0" || (q.Title.Contains(word) || q.Desc.Contains(word)))
.AsEnumerable() // randomizing should happen on client side
.OrderBy(x => random.Next())
.Skip(skip)
.Take(pageSize)
.ToList();
What is Guid.NewGuid() doing in LINQ to Entities?
This behavior when you have Guid.NewGuid() is by design in Entity Framework, it mimics SQL's ORDER BY NEWID(), to allow random ordering. When you specify a constant Guid, it merely orders by this constant value.
Picking random record from Entity Framework database without OrderBy
You can have something like :
personToCall = db.Persons.OrderBy(r => Guid.NewGuid()).Skip(toSkip).Take(1).First();
You should use FirstOrDefault
to be mode defensive.
Here the dark lord teaching the force to yoda! what is the world coming to!
Related Topics
Wpf Binding a Listbox to an Enum, Displaying the Description Attribute
Nullable<Int> VS. Int? - Is There Any Difference
Understanding .Asenumerable() in Linq to SQL
Default Parameter for Value Must Be a Compile Time Constant
How to Handle Session End in Global.Asax
C# Naming Convention for Constants
Best Way to Call a JSON Webservice from a .Net Console
How to Retrieve Data from a SQL Server Database in C#
Async Void, ASP.NET, and Count of Outstanding Operations
How to Get and Set the Window Position of Another Application in C#
Send HTML Email via C# with Smtpclient
Why Are the Properties of Anonymous Types in C# Read-Only
How to Handle JSON That Returns Both a String and a String Array
Why Are C# 4 Optional Parameters Defined on Interface Not Enforced on Implementing Class
How to Specify Proxy Credentials in Your Web.Config
Using Process.Start() to Start a Process as a Different User from Within a Windows Service