Wednesday, March 31, 2010

Random Order LINQ Query

I get a lot of requests for random ordering at my job... this helps a lot.

(from s in myset orderby Guid.NewGuid() select s).Take(5)

Updated 10/4/2011

3 comments:

  1. I tend to take the route of
    (from s in myset orderby Guid.NewGuid() select s).Take(5)

    I am on my cell atm, but it looks like yours could tentatively skip to the last element, therefore only being able to take 1 item.

    ReplyDelete
  2. hmmm. i think you're right! i'll have to change it. didn't know you could do that guid trick to be honest... thanks for bringing it up.

    where were you a year ago to help me with this then? ;)

    ReplyDelete
  3. This query is useful for random func against datatable

    var result2 = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ;

    ReplyDelete