开发者

Randomize entity framework query results

开发者 https://www.devze.com 2023-03-19 19:34 出处:网络
Good afternoon, I have a listview filled using linqdatasource + entity framework iqueryable query. The query uses a take (top on t-sql) like this:

Good afternoon,

I have a listview filled using linqdatasource + entity framework iqueryable query.

The query uses a take (top on t-sql) like this:

context.Categories().OrderBy(c=>c.Name).Take(20);

So it bring开发者_开发问答s me the 20 records I want ordered by name.

Now I want to show those 20 records on a random order. Whats the best approach acomplish this?


I believe the answer in this post is what you need:

Linq to Entities, random order

EDIT:

Get your top 20 records first. Then with the top 20 items you've already fetched, randomize them all in C#, not involving the database at all:

var yourRecords = context.Categories().OrderBy(c=>c.Name).Take(20); // I believe .Take() triggers the actual database call
yourRecords = yourRecords.OrderBy(a => Guid.NewGuid()); // then randomize the items now that they are in C# memory


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);
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消