Simplify LINQ statement getting random record

Charles Baldo
Charles Baldo used Ask the Experts™
on
Hello I have this LINQ statement.  I want to know if anyone sees a way to simplify it so I do not have to get a list then take from that list a random record

       Random rand = new Random();            
      var AdList =
                (from a in Advertisements
                 join c in Companies on a.AdvertiementOwnerID equals c.CompanyID
               where a.AdvertisementType=="Banner"
                 select new {
                    a.AdvertisementID,
                        a.AdvertisementType,
                    a.AdvertiementActive,
                    a.AdvertisementText,
                    a.AdvertisementImageLocation,
                    a.AdvertisementAlt,
                    c.CompanyName,
                    c.Website }
                ).ToList();      <-- would like to do all here                  
                        
         int toSkip = rand.Next(0, AdList.Count);  problem here do not know how to get count in above list and use it as random Max val
            var AdList2 = AdList.Skip(toSkip).Take(1);

          AdList2.Dump();      // LINQPad dumps
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Retired
Distinguished Expert 2017
Commented:
Hi charlesbaldo;

Here is a Linq to Entity Framework query which will return random records from the table. It can be configured to return one, two or more or all in random order. And the ordering is done on the server.

var AdList =
    (from a in Advertisements
     join c in Companies on a.AdvertiementOwnerID equals c.CompanyID
     where a.AdvertisementType=="Banner"
     orderby Guid.NewGuid()
     select new {
        a.AdvertisementID,
        a.AdvertisementType,
        a.AdvertiementActive,
        a.AdvertisementText, 
        a.AdvertisementImageLocation, 
        a.AdvertisementAlt, 
        c.CompanyName,
        c.Website 
    }).ToList();          // This will return all records in random order
    
//  }).FirstOrDefault();  // This will return one records randomly each time  
//  }).Take(X);           // This will return X random record

Open in new window

Charles BaldoSoftware Developer

Author

Commented:
Thank You
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Not a problem charlesaldo, glad to help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial