Sometimes a list is obtained, and I want to arrange it in a random order. In addition, if you can use different types of lists, you need to use generics.
In fact, the idea is very simple. It is to randomly retrieve an item from the original list, add it to the new list, and delete it from the original list. This is repeated until the original list is empty.
However, if you want to protect the original list from changes, you must copy a list before performing operations on copy.
Public static list <t> getrandomlist <t> (list <t> inputlist) {// copy to a array T [] copyarray = new T [inputlist. count]; inputlist. copyto (copyarray); // Add range list <t> copylist = new list <t> (); copylist. addrange (copyarray); // set outputlist and random list <t> outputlist = new list <t> (); random RD = new random (datetime. now. millisecond); While (copylist. count> 0) {// select an index and item int rdindex = RD. next (0, copylist. count-1); t remove = copylist [rdindex]; // remove it from copylist and add it to output copylist. remove (remove); outputlist. add (remove);} return outputlist ;}
Yes.
List <t> L = new list <t> ();
L. Sort (delegate (t a, t B) {return (new random (). Next (-1, 1 );});
You can also use
List <t> L = new list <t> ();
L = L. select (A => New {A, newid = guid. newguid ()}). orderby (B => B. newid ). select (C => C. a ). tolist ();