I'm new to Dynamics 365 development. I have an activity where I need to select a certain number of random records in an entity, it would be like a prize draw from a list of records. I will be working with many records. How to best do this in C#?
I'm new to Dynamics 365 development. I have an activity where I need to select a certain number of random records in an entity, it would be like a prize draw from a list of records. I will be working with many records. How to best do this in C#?
There isn't a built-in functionality to get a random record, one approach (probably is not the fastest one) is to retrieve all the records first, if you are using C# you can do a RetrieveMultiple (keep in mind that you need pagination if the records are more than 5000) with just the Id (so ColumnSet can be false).
After you retrieved the Ids you can put them in a List and access (randomly) the elements you need (check this link as an example How to access random item in list?).
Building on Guido's answer, another idea would be to get the minimum CreatedOn and maximum CreatedOn for the records in question. Then generate a random date and time within that range (inclusive of the min and max). To get the random record, query for the top 1 where CreatedOn is greater than the random date, order by CreatedOn.
Or, if you count the records first, you can generate a random number in that range and do a LINQ query with Skip(random #).Take(1).