Search code examples
c#entity-frameworklinq-to-entities

Linq to Entities, random order


How do i return matching entities in a random order?
Just to be clear this is Entity Framework stuff and LINQ to Entities.

(air code)

IEnumerable<MyEntity> results = from en in context.MyEntity
                                where en.type == myTypeVar
                                orderby ?????
                                select en;

Thanks

Edit:
I tried adding this to the context:

public Guid Random()
{
    return new Guid();
}

And using this query:

IEnumerable<MyEntity> results = from en in context.MyEntity
                                where en.type == myTypeVar
                                orderby context.Random()
                                select en;

But i got this error:

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Guid Random()' method, and this method cannot be translated into a store expression..

Edit (Current code):

IEnumerable<MyEntity> results = (from en in context.MyEntity
                                 where en.type == myTypeVar
                                 orderby context.Random()
                                 select en).AsEnumerable();

Solution

  • 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().