C # how to retrieve the child set from the List set,
Today's project requires that several pieces of data be randomly retrieved from the database and placed on the homepage. How can we randomly retrieve this subset? The method is as follows:
1. Assume that the data volume is small. For example, my database only contains 10 data records, and I want to randomly retrieve 8 data records. For this low data size, you can retrieve all data at a time and put it in the parent set, and then remove them randomly.
List <Model> list = new MyService (). queryList (). toList (); Random random = new Random (); // Note: you cannot create a random factor in the while clause, because this will cause Random factor failure. While (list. Count ()> 8) {int index = random. Next (list. Count (); list. RemoveAt (index );}
2. Assuming that the data volume is moderate, the data volume in the table I tested is 387332 pieces of data, and the id is of the uniqueidentifier type. A total of 8 pieces of data are retrieved, which takes 3 seconds. (If id is the auto-increment type of int, it will be faster ).
Random random = new Random (); StringBuilder sb = new StringBuilder (); sb. append ("select * from (select ROW_NUMBER () Over (order by a certain field) as 'x', * from tablename) as a where "); // assume that you want to obtain 8 data records from the table, int total = new MyService (). queryCount (); // assume that this is the total number of table data items int count = total/8; for (int I = 0; I <8; I ++) {if (I = 7) {// last sb. append (". x = "+ random. next (count * I, total ). toString ();} else {// not the last time Sb. append (". x = "+ random. next (count * I, count * (I + 1 )). toString () + "or") ;}} string SQL = sb. toString (); // finally obtain the SQL statement. Now we can find a random set separated by count.
3. If the data volume is huge and tens of millions of data records are obtained, the database index is required. The most common one is the auto-increment id, because order sorting by this id is equivalent to not sorting. I do not have a deep understanding of other situations. I have a lot of online materials and can only view them on my own.