Home

randomization doesn't appear to be functional in LinqPad only

(from x in FIAfterMarkets orderby Guid.NewGuid() select new {x.AfterMarketsTypeID}).First()

always give me the same row.

i've tried several variations without any luck.

Thanks
Rob

Comments

  • edited July 2014
    If I understand your question correctly this isn't going to work because Guid.NewGuid is getting executed and the result is being used to generate the sql statement. At that point you are just ordering by a constant so you get the same result every time. This is a limitation of Linq2SQL rather than linqpad.

    You will probably see something like this in the sql pane:

    SELECT * FROM (SELECT t0.AfterMarketsTypeID
    FROM FIAfterMarkets t0
    ORDER BY :p0) WHERE ROWNUM<=1
    -- p0 = [832b2367-cfec-46f3-a138-3673016d9456]


    If the table is small you could put a .AsEnumerable() in after FIAfterMarkets which would bring the whole table local and cause a guid to get generated for each row.

    For a little more efficiency you could do something along the lines of
    FIAfterMarkets
    .OrderBy(e => e.AfterMarketsTypeID)
    .Skip(rnd.Next(FIAfterMarkets.Count()))
    .Select(e => e.AfterMarketsTypeID).First()

    Hope that helps
Sign In or Register to comment.