<p>I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a <code>List&lt;string&gt;</code>.</p>

[{'answer_id': 48089, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 8, 'selected': True, 'text': '<p>Iterate through and for each element make the probability of selection = (number needed)/(number left)</p>\n<p>So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you\'ll have all of them before that.</p>\n<p>This technique is called <a href="https://stackoverflow.com/questions/35065764/select-n-records-at-random-from-a-set-of-n">selection sampling</a>, a special case of <a href="https://en.wikipedia.org/wiki/Reservoir_sampling" rel="noreferrer">Reservoir Sampling</a>. It\'s similar in performance to shuffling the input, but of course allows the sample to be generated without modifying the original data.</p>\n'}, {'answer_id': 48114, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 5, 'selected': False, 'text': '<p>This is actually a harder problem than it sounds like, mainly because many mathematically-correct solutions will fail to actually allow you to hit all the possibilities (more on this below).</p>\n\n<p>First, here are some easy-to-implement, correct-if-you-have-a-truly-random-number generator:</p>\n\n<p>(0) Kyle\'s answer, which is O(n).</p>\n\n<p>(1) Generate a list of n pairs [(0, rand), (1, rand), (2, rand), ...], sort them by the second coordinate, and use the first k (for you, k=5) indices to get your random subset.  I think this is easy to implement, although it is O(n log n) time.</p>\n\n<p>(2) Init an empty list s = [] that will grow to be the indices of k random elements.  Choose a number r in {0, 1, 2, ..., n-1} at random, r = rand % n, and add this to s.  Next take r = rand % (n-1) and stick in s; add to r the # elements less than it in s to avoid collisions.  Next take r = rand % (n-2), and do the same thing, etc. until you have k distinct elements in s.  This has worst-case running time O(k^2).  So for k &lt;&lt; n, this can be faster.  If you keep s sorted and track which contiguous intervals it has, you can implement it in O(k log k), but it\'s more work.</p>\n\n<p>@Kyle - you\'re right, on second thought I agree with your answer.  I hastily read it at first, and mistakenly thought you were indicating to sequentially choose each element with fixed probability k/n, which would have been wrong - but your adaptive approach appears correct to me.  Sorry about that.</p>\n\n<p>Ok, and now for the kicker: asymptotically (for fixed k, n growing), there are n^k/k! choices of k element subset out of n elements [this is an approximation of (n choose k)].  If n is large, and k is not very small, then these numbers are huge.  The best cycle length you can hope for in any standard 32 bit random number generator is 2^32 = 256^4.  So if we have a list of 1000 elements, and we want to choose 5 at random, there\'s no way a standard random number generator will hit all the possibilities.  However, as long as you\'re ok with a choice that works fine for smaller sets, and always "looks" random, then these algorithms should be ok.</p>\n\n<p><strong>Addendum</strong>: After writing this, I realized that it\'s tricky to implement idea (2) correctly, so I wanted to clarify this answer.  To get O(k log k) time, you need an array-like structure that supports O(log m) searches and inserts - a balanced binary tree can do this.  Using such a structure to build up an array called s, here is some pseudopython:</p>\n\n<pre><code># Returns a container s with k distinct random numbers from {0, 1, ..., n-1}\ndef ChooseRandomSubset(n, k):\n  for i in range(k):\n    r = UniformRandom(0, n-i)                 # May be 0, must be &lt; n-i\n    q = s.FirstIndexSuchThat( s[q] - q &gt; r )  # This is the search.\n    s.InsertInOrder(q ? r + q : r + len(s))   # Inserts right before q.\n  return s\n</code></pre>\n\n<p>I suggest running through a few sample cases to see how this efficiently implements the above English explanation.</p>\n'}, {'answer_id': 48138, 'author': 'IanStallings', 'author_id': 4933, 'author_profile': 'https://Stackoverflow.com/users/4933', 'pm_score': 2, 'selected': False, 'text': "<p>This is the best I could come up with on a first cut:</p>\n\n<pre><code>public List&lt;String&gt; getRandomItemsFromList(int returnCount, List&lt;String&gt; list)\n{\n    List&lt;String&gt; returnList = new List&lt;String&gt;();\n    Dictionary&lt;int, int&gt; randoms = new Dictionary&lt;int, int&gt;();\n\n    while (randoms.Count != returnCount)\n    {\n        //generate new random between one and total list count\n        int randomInt = new Random().Next(list.Count);\n\n        // store this in dictionary to ensure uniqueness\n        try\n        {\n            randoms.Add(randomInt, randomInt);\n        }\n        catch (ArgumentException aex)\n        {\n            Console.Write(aex.Message);\n        } //we can assume this element exists in the dictonary already \n\n        //check for randoms length and then iterate through the original list \n        //adding items we select via random to the return list\n        if (randoms.Count == returnCount)\n        {\n            foreach (int key in randoms.Keys)\n                returnList.Add(list[randoms[key]]);\n\n            break; //break out of _while_ loop\n        }\n    }\n\n    return returnList;\n}\n</code></pre>\n\n<p>Using a list of randoms within a range of 1 - total list count and then simply pulling those items in the list seemed to be the best way, but using the Dictionary to ensure uniqueness is something I'm still mulling over.</p>\n\n<p>Also note I used a string list, replace as needed.</p>\n"}, {'answer_id': 48141, 'author': 'spoulson', 'author_id': 3347, 'author_profile': 'https://Stackoverflow.com/users/3347', 'pm_score': 3, 'selected': False, 'text': '<p>From <a href="http://mcherm.com/permalinks/1/a-random-selection-algorithm" rel="nofollow noreferrer">Dragons in the Algorithm</a>, an interpretation in C#:</p>\n\n<pre><code>int k = 10; // items to select\nvar items = new List&lt;int&gt;(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });\nvar selected = new List&lt;int&gt;();\ndouble needed = k;\ndouble available = items.Count;\nvar rand = new Random();\nwhile (selected.Count &lt; k) {\n   if( rand.NextDouble() &lt; needed / available ) {\n      selected.Add(items[(int)available-1])\n      needed--;\n   }\n   available--;\n}\n</code></pre>\n\n<p>This algorithm will select unique indicies of the items list.</p>\n'}, {'answer_id': 48188, 'author': 'hitec', 'author_id': 120, 'author_profile': 'https://Stackoverflow.com/users/120', 'pm_score': 0, 'selected': False, 'text': '<p>I recently did this on my project using an idea similar to <a href="https://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c#48114">Tyler\'s point 1</a>.<br>\nI was loading a bunch of questions and selecting five at random. Sorting was achieved using an <a href="http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx" rel="nofollow noreferrer">IComparer</a>.<br>\naAll questions were loaded in the a QuestionSorter list, which was then sorted using the <a href="http://msdn.microsoft.com/en-us/library/234b841s.aspx" rel="nofollow noreferrer">List\'s Sort function</a> and the first k elements where selected.</p>\n\n<pre><code>    private class QuestionSorter : IComparable&lt;QuestionSorter&gt;\n    {\n        public double SortingKey\n        {\n            get;\n            set;\n        }\n\n        public Question QuestionObject\n        {\n            get;\n            set;\n        }\n\n        public QuestionSorter(Question q)\n        {\n            this.SortingKey = RandomNumberGenerator.RandomDouble;\n            this.QuestionObject = q;\n        }\n\n        public int CompareTo(QuestionSorter other)\n        {\n            if (this.SortingKey &lt; other.SortingKey)\n            {\n                return -1;\n            }\n            else if (this.SortingKey &gt; other.SortingKey)\n            {\n                return 1;\n            }\n            else\n            {\n                return 0;\n            }\n        }\n    }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>    List&lt;QuestionSorter&gt; unsortedQuestions = new List&lt;QuestionSorter&gt;();\n\n    // add the questions here\n\n    unsortedQuestions.Sort(unsortedQuestions as IComparer&lt;QuestionSorter&gt;);\n\n    // select the first k elements\n</code></pre>\n'}, {'answer_id': 250976, 'author': 'Cameron A. Ellis', 'author_id': 1748529, 'author_profile': 'https://Stackoverflow.com/users/1748529', 'pm_score': 0, 'selected': False, 'text': '<p>why not something like this:</p>\n\n<pre><code> Dim ar As New ArrayList\n    Dim numToGet As Integer = 5\n    \'hard code just to test\n    ar.Add("12")\n    ar.Add("11")\n    ar.Add("10")\n    ar.Add("15")\n    ar.Add("16")\n    ar.Add("17")\n\n    Dim randomListOfProductIds As New ArrayList\n\n    Dim toAdd As String = ""\n    For i = 0 To numToGet - 1\n        toAdd = ar(CInt((ar.Count - 1) * Rnd()))\n\n        randomListOfProductIds.Add(toAdd)\n        \'remove from id list\n        ar.Remove(toAdd)\n\n    Next\n\'sorry i\'m lazy and have to write vb at work :( and didn\'t feel like converting to c#\n</code></pre>\n'}, {'answer_id': 451540, 'author': 'Frank Schwieterman', 'author_id': 32203, 'author_profile': 'https://Stackoverflow.com/users/32203', 'pm_score': 4, 'selected': False, 'text': '<p>I think the selected answer is correct and pretty sweet.  I implemented it differently though, as I also wanted the result in random order.</p>\n\n<pre><code>    static IEnumerable&lt;SomeType&gt; PickSomeInRandomOrder&lt;SomeType&gt;(\n        IEnumerable&lt;SomeType&gt; someTypes,\n        int maxCount)\n    {\n        Random random = new Random(DateTime.Now.Millisecond);\n\n        Dictionary&lt;double, SomeType&gt; randomSortTable = new Dictionary&lt;double,SomeType&gt;();\n\n        foreach(SomeType someType in someTypes)\n            randomSortTable[random.NextDouble()] = someType;\n\n        return randomSortTable.OrderBy(KVP =&gt; KVP.Key).Take(maxCount).Select(KVP =&gt; KVP.Value);\n    }\n</code></pre>\n'}, {'answer_id': 1042863, 'author': 'Tobias Hertkorn', 'author_id': 33827, 'author_profile': 'https://Stackoverflow.com/users/33827', 'pm_score': 1, 'selected': False, 'text': '<p>It is a lot harder than one would think. See the <a href="http://www.codinghorror.com/blog/archives/001008.html" rel="nofollow noreferrer">great Article "Shuffling"</a> from Jeff.</p>\n\n<p>I did write a very short article on that subject including C# code:<br>\n<a href="http://saftsack.fs.uni-bayreuth.de/~dun3/archives/return-random-subset-of-n-elements-of-a-given-array/98.html" rel="nofollow noreferrer">Return random subset of N elements of a given array</a></p>\n'}, {'answer_id': 2312911, 'author': 'Ers', 'author_id': 205743, 'author_profile': 'https://Stackoverflow.com/users/205743', 'pm_score': 8, 'selected': False, 'text': '<p>Using linq:</p>\n\n<pre><code>YourList.OrderBy(x =&gt; rnd.Next()).Take(5)\n</code></pre>\n'}, {'answer_id': 3288539, 'author': 'Tine M.', 'author_id': 315524, 'author_profile': 'https://Stackoverflow.com/users/315524', 'pm_score': 2, 'selected': False, 'text': "<p>The simple solution I use (probably not good for large lists):\nCopy the list into temporary list, then in loop randomly select Item from temp list and put it in selected items list while removing it form temp list (so it can't be reselected).</p>\n\n<p>Example:</p>\n\n<pre><code>List&lt;Object&gt; temp = OriginalList.ToList();\nList&lt;Object&gt; selectedItems = new List&lt;Object&gt;();\nRandom rnd = new Random();\nObject o;\nint i = 0;\nwhile (i &lt; NumberOfSelectedItems)\n{\n            o = temp[rnd.Next(temp.Count)];\n            selectedItems.Add(o);\n            temp.Remove(o);\n            i++;\n }\n</code></pre>\n"}, {'answer_id': 3530489, 'author': 'Kristofer', 'author_id': 348439, 'author_profile': 'https://Stackoverflow.com/users/348439', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s my approach (full text here <a href="http://krkadev.blogspot.com/2010/08/random-numbers-without-repetition.html" rel="nofollow noreferrer">http://krkadev.blogspot.com/2010/08/random-numbers-without-repetition.html</a> ).</p>\n\n<p>It should run in O(K) instead of O(N), where K is the number of wanted elements and N is the size of the list to choose from:</p>\n\n<pre><code>public &lt;T&gt; List&lt;T&gt; take(List&lt;T&gt; source, int k) {\n int n = source.size();\n if (k &gt; n) {\n   throw new IllegalStateException(\n     "Can not take " + k +\n     " elements from a list with " + n +\n     " elements");\n }\n List&lt;T&gt; result = new ArrayList&lt;T&gt;(k);\n Map&lt;Integer,Integer&gt; used = new HashMap&lt;Integer,Integer&gt;();\n int metric = 0;\n for (int i = 0; i &lt; k; i++) {\n   int off = random.nextInt(n - i);\n   while (true) {\n     metric++;\n     Integer redirect = used.put(off, n - i - 1);\n     if (redirect == null) {\n       break;\n     }\n     off = redirect;\n   }\n   result.add(source.get(off));\n }\n assert metric &lt;= 2*k;\n return result;\n}\n</code></pre>\n'}, {'answer_id': 8876593, 'author': 'dhakim', 'author_id': 1151342, 'author_profile': 'https://Stackoverflow.com/users/1151342', 'pm_score': 4, 'selected': False, 'text': '<p>I just ran into this problem, and some more google searching brought me to the problem of randomly shuffling a list: <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle">http://en.wikipedia.org/wiki/Fisher-Yates_shuffle</a></p>\n\n<p>To completely randomly shuffle your list (in place) you do this:</p>\n\n<p>To shuffle an array a of n elements (indices 0..n-1):</p>\n\n<pre><code>  for i from n − 1 downto 1 do\n       j ← random integer with 0 ≤ j ≤ i\n       exchange a[j] and a[i]\n</code></pre>\n\n<p>If you only need the first 5 elements, then instead of running i all the way from n-1 to 1, you only need to run it to n-5  (ie: n-5)</p>\n\n<p>Lets say you need k items, </p>\n\n<p>This becomes:</p>\n\n<pre><code>  for (i = n − 1; i &gt;= n-k; i--)\n  {\n       j = random integer with 0 ≤ j ≤ i\n       exchange a[j] and a[i]\n  }\n</code></pre>\n\n<p>Each item that is selected is swapped toward the end of the array, so the k elements selected are the last k elements of the array.  </p>\n\n<p>This takes time O(k), where k is the number of randomly selected elements you need.  </p>\n\n<p>Further, if you don\'t want to modify your initial list, you can write down all your swaps in a temporary list, reverse that list, and apply them again, thus performing the inverse set of swaps and returning you your initial list without changing the O(k) running time.  </p>\n\n<p>Finally, for the real stickler, if (n == k), you should stop at 1, not n-k, as the randomly chosen integer will always be 0.  </p>\n'}, {'answer_id': 9842947, 'author': 'Marwan Roushdy', 'author_id': 964658, 'author_profile': 'https://Stackoverflow.com/users/964658', 'pm_score': 3, 'selected': False, 'text': '<p>You can use this but the ordering will happen on client side</p>\n\n<pre><code> .AsEnumerable().OrderBy(n =&gt; Guid.NewGuid()).Take(5);\n</code></pre>\n'}, {'answer_id': 12654300, 'author': 'vag', 'author_id': 1708444, 'author_profile': 'https://Stackoverflow.com/users/1708444', 'pm_score': 6, 'selected': False, 'text': '<pre><code>public static List&lt;T&gt; GetRandomElements&lt;T&gt;(this IEnumerable&lt;T&gt; list, int elementsCount)\n{\n    return list.OrderBy(arg =&gt; Guid.NewGuid()).Take(elementsCount).ToList();\n}\n</code></pre>\n'}, {'answer_id': 13537208, 'author': 'nawfal', 'author_id': 661933, 'author_profile': 'https://Stackoverflow.com/users/661933', 'pm_score': 3, 'selected': False, 'text': '<p>Selecting N <strong>random</strong> items from a group shouldn\'t have anything to do with <strong>order</strong>! Randomness is about unpredictability and not about shuffling positions in a group. All the answers that deal with some kinda ordering is bound to be less efficient than the ones that do not. Since efficiency is the key here, I will post something that doesn\'t change the order of items too much.</p>\n\n<p>1) If you need <strong>true</strong> random values which means there is no restriction on which elements to choose from (ie, once chosen item can be reselected): </p>\n\n<pre><code>public static List&lt;T&gt; GetTrueRandom&lt;T&gt;(this IList&lt;T&gt; source, int count, \n                                       bool throwArgumentOutOfRangeException = true)\n{\n    if (throwArgumentOutOfRangeException &amp;&amp; count &gt; source.Count)\n        throw new ArgumentOutOfRangeException();\n\n    var randoms = new List&lt;T&gt;(count);\n    randoms.AddRandomly(source, count);\n    return randoms;\n}\n</code></pre>\n\n<p>If you set the exception flag off, then you can choose random items any number of times.</p>\n\n<blockquote>\n  <p>If you have { 1, 2, 3, 4 }, then it can give { 1, 4, 4 }, { 1, 4, 3 } etc for 3 items or even { 1, 4, 3, 2, 4 } for 5 items!</p>\n</blockquote>\n\n<p>This should be pretty fast, as it has nothing to check.</p>\n\n<p>2) If you need <strong>individual</strong> members from the group with no repetition, then I would rely on a dictionary (as many have pointed out already).</p>\n\n<pre><code>public static List&lt;T&gt; GetDistinctRandom&lt;T&gt;(this IList&lt;T&gt; source, int count)\n{\n    if (count &gt; source.Count)\n        throw new ArgumentOutOfRangeException();\n\n    if (count == source.Count)\n        return new List&lt;T&gt;(source);\n\n    var sourceDict = source.ToIndexedDictionary();\n\n    if (count &gt; source.Count / 2)\n    {\n        while (sourceDict.Count &gt; count)\n            sourceDict.Remove(source.GetRandomIndex());\n\n        return sourceDict.Select(kvp =&gt; kvp.Value).ToList();\n    }\n\n    var randomDict = new Dictionary&lt;int, T&gt;(count);\n    while (randomDict.Count &lt; count)\n    {\n        int key = source.GetRandomIndex();\n        if (!randomDict.ContainsKey(key))\n            randomDict.Add(key, sourceDict[key]);\n    }\n\n    return randomDict.Select(kvp =&gt; kvp.Value).ToList();\n}\n</code></pre>\n\n<p>The code is a bit lengthier than other dictionary approaches here because I\'m not only adding, but also removing from list, so its kinda two loops. You can see here that I have not <strong>reordered</strong> anything at all when <code>count</code> becomes equal to <code>source.Count</code>. That\'s because I believe <strong>randomness should be in the <em>returned set</em> as a whole</strong>. I mean if you want <strong>5</strong> random items from <code>1, 2, 3, 4, 5</code>, it shouldn\'t matter if its <code>1, 3, 4, 2, 5</code> or <code>1, 2, 3, 4, 5</code>, but if you need <strong>4</strong> items from the same set, then it should unpredictably yield in <code>1, 2, 3, 4</code>, <code>1, 3, 5, 2</code>, <code>2, 3, 5, 4</code> etc. Secondly, <strong>when the count of random items to be returned is more than half of the original group, then its easier to remove <code>source.Count - count</code> items from the group</strong> than adding <code>count</code> items. For performance reasons I have used <code>source</code> instead of <code>sourceDict</code> to get then random index in the remove method.</p>\n\n<blockquote>\n  <p>So if you have { 1, 2, 3, 4 }, this can end up in { 1, 2, 3 }, { 3, 4, 1 } etc for 3 items.</p>\n</blockquote>\n\n<p>3) If you need truly distinct random values from your group by taking into account the duplicates in the original group, then you may use the same approach as above, but a <code>HashSet</code> will be lighter than a dictionary.</p>\n\n<pre><code>public static List&lt;T&gt; GetTrueDistinctRandom&lt;T&gt;(this IList&lt;T&gt; source, int count, \n                                               bool throwArgumentOutOfRangeException = true)\n{\n    if (count &gt; source.Count)\n        throw new ArgumentOutOfRangeException();\n\n    var set = new HashSet&lt;T&gt;(source);\n\n    if (throwArgumentOutOfRangeException &amp;&amp; count &gt; set.Count)\n        throw new ArgumentOutOfRangeException();\n\n    List&lt;T&gt; list = hash.ToList();\n\n    if (count &gt;= set.Count)\n        return list;\n\n    if (count &gt; set.Count / 2)\n    {\n        while (set.Count &gt; count)\n            set.Remove(list.GetRandom());\n\n        return set.ToList();\n    }\n\n    var randoms = new HashSet&lt;T&gt;();\n    randoms.AddRandomly(list, count);\n    return randoms.ToList();\n}\n</code></pre>\n\n<p>The <code>randoms</code> variable is made a <code>HashSet</code> to avoid duplicates being added in the rarest of rarest cases where <code>Random.Next</code> can yield the same value, especially when input list is small.</p>\n\n<blockquote>\n  <p>So { 1, 2, 2, 4 } => 3 random items => { 1, 2, 4 } and never { 1, 2, 2}</p>\n  \n  <p>{ 1, 2, 2, 4 } => 4 random items => exception!! or { 1, 2, 4 } depending on the flag set.</p>\n</blockquote>\n\n<p>Some of the extension methods I have used:</p>\n\n<pre><code>static Random rnd = new Random();\npublic static int GetRandomIndex&lt;T&gt;(this ICollection&lt;T&gt; source)\n{\n    return rnd.Next(source.Count);\n}\n\npublic static T GetRandom&lt;T&gt;(this IList&lt;T&gt; source)\n{\n    return source[source.GetRandomIndex()];\n}\n\nstatic void AddRandomly&lt;T&gt;(this ICollection&lt;T&gt; toCol, IList&lt;T&gt; fromList, int count)\n{\n    while (toCol.Count &lt; count)\n        toCol.Add(fromList.GetRandom());\n}\n\npublic static Dictionary&lt;int, T&gt; ToIndexedDictionary&lt;T&gt;(this IEnumerable&lt;T&gt; lst)\n{\n    return lst.ToIndexedDictionary(t =&gt; t);\n}\n\npublic static Dictionary&lt;int, T&gt; ToIndexedDictionary&lt;S, T&gt;(this IEnumerable&lt;S&gt; lst, \n                                                           Func&lt;S, T&gt; valueSelector)\n{\n    int index = -1;\n    return lst.ToDictionary(t =&gt; ++index, valueSelector);\n}\n</code></pre>\n\n<p>If its all about performance with tens of 1000s of items in the list having to be iterated 10000 times, then you may want to have <a href="http://www.codeproject.com/Articles/9187/A-fast-equivalent-for-System-Random" rel="nofollow noreferrer">faster random class</a> than <code>System.Random</code>, but I don\'t think that\'s a big deal considering the latter most probably is never a bottleneck, its quite fast enough..</p>\n\n<p><strong>Edit:</strong> If you need to re-arrange order of returned items as well, then there\'s nothing that can beat <a href="https://stackoverflow.com/a/8876593/661933">dhakim\'s Fisher-Yates approach</a> - short, sweet and simple..</p>\n'}, {'answer_id': 16663098, 'author': 'apdnu', 'author_id': 1103939, 'author_profile': 'https://Stackoverflow.com/users/1103939', 'pm_score': 0, 'selected': False, 'text': "<p>This isn't as elegant or efficient as the accepted solution, but it's quick to write up. First, permute the array randomly, then select the first K elements. In python,</p>\n\n<pre><code>import numpy\n\nN = 20\nK = 5\n\nidx = np.arange(N)\nnumpy.random.shuffle(idx)\n\nprint idx[:K]\n</code></pre>\n"}, {'answer_id': 17244160, 'author': 'drzaus', 'author_id': 1037948, 'author_profile': 'https://Stackoverflow.com/users/1037948', 'pm_score': 3, 'selected': False, 'text': '<p>Was thinking about comment by @JohnShedletsky on the <a href="https://stackoverflow.com/a/48089/1037948">accepted answer</a> regarding (paraphrase):</p>\n\n<blockquote>\n  <p>you should be able to to this in O(subset.Length), rather than O(originalList.Length)</p>\n</blockquote>\n\n<p>Basically, you should be able to generate <code>subset</code> random indices and then pluck them from the original list.</p>\n\n<h2>The Method</h2>\n\n<pre><code>public static class EnumerableExtensions {\n\n    public static Random randomizer = new Random(); // you\'d ideally be able to replace this with whatever makes you comfortable\n\n    public static IEnumerable&lt;T&gt; GetRandom&lt;T&gt;(this IEnumerable&lt;T&gt; list, int numItems) {\n        return (list as T[] ?? list.ToArray()).GetRandom(numItems);\n\n        // because ReSharper whined about duplicate enumeration...\n        /*\n        items.Add(list.ElementAt(randomizer.Next(list.Count()))) ) numItems--;\n        */\n    }\n\n    // just because the parentheses were getting confusing\n    public static IEnumerable&lt;T&gt; GetRandom&lt;T&gt;(this T[] list, int numItems) {\n        var items = new HashSet&lt;T&gt;(); // don\'t want to add the same item twice; otherwise use a list\n        while (numItems &gt; 0 )\n            // if we successfully added it, move on\n            if( items.Add(list[randomizer.Next(list.Length)]) ) numItems--;\n\n        return items;\n    }\n\n    // and because it\'s really fun; note -- you may get repetition\n    public static IEnumerable&lt;T&gt; PluckRandomly&lt;T&gt;(this IEnumerable&lt;T&gt; list) {\n        while( true )\n            yield return list.ElementAt(randomizer.Next(list.Count()));\n    }\n\n}\n</code></pre>\n\n<p>If you wanted to be even more efficient, you would probably use a <code>HashSet</code> of the <strong>indices</strong>, not the actual list elements (in case you\'ve got complex types or expensive comparisons);</p>\n\n<h2>The Unit Test</h2>\n\n<p>And to make sure we don\'t have any collisions, etc.</p>\n\n<pre><code>[TestClass]\npublic class RandomizingTests : UnitTestBase {\n    [TestMethod]\n    public void GetRandomFromList() {\n        this.testGetRandomFromList((list, num) =&gt; list.GetRandom(num));\n    }\n\n    [TestMethod]\n    public void PluckRandomly() {\n        this.testGetRandomFromList((list, num) =&gt; list.PluckRandomly().Take(num), requireDistinct:false);\n    }\n\n    private void testGetRandomFromList(Func&lt;IEnumerable&lt;int&gt;, int, IEnumerable&lt;int&gt;&gt; methodToGetRandomItems, int numToTake = 10, int repetitions = 100000, bool requireDistinct = true) {\n        var items = Enumerable.Range(0, 100);\n        IEnumerable&lt;int&gt; randomItems = null;\n\n        while( repetitions-- &gt; 0 ) {\n            randomItems = methodToGetRandomItems(items, numToTake);\n            Assert.AreEqual(numToTake, randomItems.Count(),\n                            "Did not get expected number of items {0}; failed at {1} repetition--", numToTake, repetitions);\n            if(requireDistinct) Assert.AreEqual(numToTake, randomItems.Distinct().Count(),\n                            "Collisions (non-unique values) found, failed at {0} repetition--", repetitions);\n            Assert.IsTrue(randomItems.All(o =&gt; items.Contains(o)),\n                        "Some unknown values found; failed at {0} repetition--", repetitions);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 17598162, 'author': 'Tom Gullen', 'author_id': 356635, 'author_profile': 'https://Stackoverflow.com/users/356635', 'pm_score': 2, 'selected': False, 'text': '<p>Based on Kyle\'s answer, here\'s my c# implementation.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Picks random selection of available game ID\'s\n/// &lt;/summary&gt;\nprivate static List&lt;int&gt; GetRandomGameIDs(int count)\n{       \n    var gameIDs = (int[])HttpContext.Current.Application["NonDeletedArcadeGameIDs"];\n    var totalGameIDs = gameIDs.Count();\n    if (count &gt; totalGameIDs) count = totalGameIDs;\n\n    var rnd = new Random();\n    var leftToPick = count;\n    var itemsLeft = totalGameIDs;\n    var arrPickIndex = 0;\n    var returnIDs = new List&lt;int&gt;();\n    while (leftToPick &gt; 0)\n    {\n        if (rnd.Next(0, itemsLeft) &lt; leftToPick)\n        {\n            returnIDs .Add(gameIDs[arrPickIndex]);\n            leftToPick--;\n        }\n        arrPickIndex++;\n        itemsLeft--;\n    }\n\n    return returnIDs ;\n}\n</code></pre>\n'}, {'answer_id': 28186730, 'author': 'Alex Gilbert', 'author_id': 4501713, 'author_profile': 'https://Stackoverflow.com/users/4501713', 'pm_score': 2, 'selected': False, 'text': "<p>This method may be equivalent to Kyle's. </p>\n\n<p>Say your list is of size n and you want k elements. </p>\n\n<pre><code>Random rand = new Random();\nfor(int i = 0; k&gt;0; ++i) \n{\n    int r = rand.Next(0, n-i);\n    if(r&lt;k) \n    {\n        //include element i\n        k--;\n    }\n} \n</code></pre>\n\n<p>Works like a charm :) </p>\n\n<p>-Alex Gilbert    </p>\n"}, {'answer_id': 30925976, 'author': 'Paul Chernoch', 'author_id': 127251, 'author_profile': 'https://Stackoverflow.com/users/127251', 'pm_score': 3, 'selected': False, 'text': '<p>I combined several of the above answers to create a Lazily-evaluated extension method. My testing showed that Kyle\'s approach (Order(N)) is many times slower than drzaus\' use of a set to propose the random indices to choose (Order(K)). The former performs many more calls to the random number generator, plus iterates more times over the items.</p>\n\n<p>The goals of my implementation were:</p>\n\n<p>1) Do not realize the full list if given an IEnumerable that is not an IList. If I am given a sequence of a zillion items, I do not want to run out of memory. Use Kyle\'s approach for an on-line solution.</p>\n\n<p>2) If I can tell that it is an IList, use drzaus\' approach, with a twist. If K is more than half of N, I risk thrashing as I choose many random indices again and again and have to skip them. Thus I compose a list of the indices to NOT keep.</p>\n\n<p>3) I guarantee that the items will be returned in the same order that they were encountered. Kyle\'s algorithm required no alteration. drzaus\' algorithm required that I not emit items in the order that the random indices are chosen. I gather all the indices into a SortedSet, then emit items in sorted index order.</p>\n\n<p>4) If K is large compared to N and I invert the sense of the set, then I enumerate all items and test if the index is not in the set. This means that\nI lose the Order(K) run time, but since K is close to N in these cases, I do not lose much.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Takes k elements from the next n elements at random, preserving their order.\n    /// \n    /// If there are fewer than n elements in items, this may return fewer than k elements.\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name="TElem"&gt;Type of element in the items collection.&lt;/typeparam&gt;\n    /// &lt;param name="items"&gt;Items to be randomly selected.&lt;/param&gt;\n    /// &lt;param name="k"&gt;Number of items to pick.&lt;/param&gt;\n    /// &lt;param name="n"&gt;Total number of items to choose from.\n    /// If the items collection contains more than this number, the extra members will be skipped.\n    /// If the items collection contains fewer than this number, it is possible that fewer than k items will be returned.&lt;/param&gt;\n    /// &lt;returns&gt;Enumerable over the retained items.\n    /// \n    /// See http://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c-sharp for the commentary.\n    /// &lt;/returns&gt;\n    public static IEnumerable&lt;TElem&gt; TakeRandom&lt;TElem&gt;(this IEnumerable&lt;TElem&gt; items, int k, int n)\n    {\n        var r = new FastRandom();\n        var itemsList = items as IList&lt;TElem&gt;;\n\n        if (k &gt;= n || (itemsList != null &amp;&amp; k &gt;= itemsList.Count))\n            foreach (var item in items) yield return item;\n        else\n        {  \n            // If we have a list, we can infer more information and choose a better algorithm.\n            // When using an IList, this is about 7 times faster (on one benchmark)!\n            if (itemsList != null &amp;&amp; k &lt; n/2)\n            {\n                // Since we have a List, we can use an algorithm suitable for Lists.\n                // If there are fewer than n elements, reduce n.\n                n = Math.Min(n, itemsList.Count);\n\n                // This algorithm picks K index-values randomly and directly chooses those items to be selected.\n                // If k is more than half of n, then we will spend a fair amount of time thrashing, picking\n                // indices that we have already picked and having to try again.   \n                var invertSet = k &gt;= n/2;  \n                var positions = invertSet ? (ISet&lt;int&gt;) new HashSet&lt;int&gt;() : (ISet&lt;int&gt;) new SortedSet&lt;int&gt;();\n\n                var numbersNeeded = invertSet ? n - k : k;\n                while (numbersNeeded &gt; 0)\n                    if (positions.Add(r.Next(0, n))) numbersNeeded--;\n\n                if (invertSet)\n                {\n                    // positions contains all the indices of elements to Skip.\n                    for (var itemIndex = 0; itemIndex &lt; n; itemIndex++)\n                    {\n                        if (!positions.Contains(itemIndex))\n                            yield return itemsList[itemIndex];\n                    }\n                }\n                else\n                {\n                    // positions contains all the indices of elements to Take.\n                    foreach (var itemIndex in positions)\n                        yield return itemsList[itemIndex];              \n                }\n            }\n            else\n            {\n                // Since we do not have a list, we will use an online algorithm.\n                // This permits is to skip the rest as soon as we have enough items.\n                var found = 0;\n                var scanned = 0;\n                foreach (var item in items)\n                {\n                    var rand = r.Next(0,n-scanned);\n                    if (rand &lt; k - found)\n                    {\n                        yield return item;\n                        found++;\n                    }\n                    scanned++;\n                    if (found &gt;= k || scanned &gt;= n)\n                        break;\n                }\n            }\n        }  \n    } \n</code></pre>\n\n<p>I use a specialized random number generator, but you can just use C#\'s <strong>Random</strong> if you want. (<strong>FastRandom</strong> was written by Colin Green and is part of SharpNEAT. It has a period of 2^128-1 which is better than many RNGs.)</p>\n\n<p>Here are the unit tests:</p>\n\n<pre><code>[TestClass]\npublic class TakeRandomTests\n{\n    /// &lt;summary&gt;\n    /// Ensure that when randomly choosing items from an array, all items are chosen with roughly equal probability.\n    /// &lt;/summary&gt;\n    [TestMethod]\n    public void TakeRandom_Array_Uniformity()\n    {\n        const int numTrials = 2000000;\n        const int expectedCount = numTrials/20;\n        var timesChosen = new int[100];\n        var century = new int[100];\n        for (var i = 0; i &lt; century.Length; i++)\n            century[i] = i;\n\n        for (var trial = 0; trial &lt; numTrials; trial++)\n        {\n            foreach (var i in century.TakeRandom(5, 100))\n                timesChosen[i]++;\n        }\n        var avg = timesChosen.Average();\n        var max = timesChosen.Max();\n        var min = timesChosen.Min();\n        var allowedDifference = expectedCount/100;\n        AssertBetween(avg, expectedCount - 2, expectedCount + 2, "Average");\n        //AssertBetween(min, expectedCount - allowedDifference, expectedCount, "Min");\n        //AssertBetween(max, expectedCount, expectedCount + allowedDifference, "Max");\n\n        var countInRange = timesChosen.Count(i =&gt; i &gt;= expectedCount - allowedDifference &amp;&amp; i &lt;= expectedCount + allowedDifference);\n        Assert.IsTrue(countInRange &gt;= 90, String.Format("Not enough were in range: {0}", countInRange));\n    }\n\n    /// &lt;summary&gt;\n    /// Ensure that when randomly choosing items from an IEnumerable that is not an IList, \n    /// all items are chosen with roughly equal probability.\n    /// &lt;/summary&gt;\n    [TestMethod]\n    public void TakeRandom_IEnumerable_Uniformity()\n    {\n        const int numTrials = 2000000;\n        const int expectedCount = numTrials / 20;\n        var timesChosen = new int[100];\n\n        for (var trial = 0; trial &lt; numTrials; trial++)\n        {\n            foreach (var i in Range(0,100).TakeRandom(5, 100))\n                timesChosen[i]++;\n        }\n        var avg = timesChosen.Average();\n        var max = timesChosen.Max();\n        var min = timesChosen.Min();\n        var allowedDifference = expectedCount / 100;\n        var countInRange =\n            timesChosen.Count(i =&gt; i &gt;= expectedCount - allowedDifference &amp;&amp; i &lt;= expectedCount + allowedDifference);\n        Assert.IsTrue(countInRange &gt;= 90, String.Format("Not enough were in range: {0}", countInRange));\n    }\n\n    private IEnumerable&lt;int&gt; Range(int low, int count)\n    {\n        for (var i = low; i &lt; low + count; i++)\n            yield return i;\n    }\n\n    private static void AssertBetween(int x, int low, int high, String message)\n    {\n        Assert.IsTrue(x &gt; low, String.Format("Value {0} is less than lower limit of {1}. {2}", x, low, message));\n        Assert.IsTrue(x &lt; high, String.Format("Value {0} is more than upper limit of {1}. {2}", x, high, message));\n    }\n\n    private static void AssertBetween(double x, double low, double high, String message)\n    {\n        Assert.IsTrue(x &gt; low, String.Format("Value {0} is less than lower limit of {1}. {2}", x, low, message));\n        Assert.IsTrue(x &lt; high, String.Format("Value {0} is more than upper limit of {1}. {2}", x, high, message));\n    }\n}\n</code></pre>\n'}, {'answer_id': 32066958, 'author': 'Kvam', 'author_id': 1392287, 'author_profile': 'https://Stackoverflow.com/users/1392287', 'pm_score': 0, 'selected': False, 'text': '<p>I would use an extension method.</p>\n\n<pre><code>    public static IEnumerable&lt;T&gt; TakeRandom&lt;T&gt;(this IEnumerable&lt;T&gt; elements, int countToTake)\n    {\n        var random = new Random();\n\n        var internalList = elements.ToList();\n\n        var selected = new List&lt;T&gt;();\n        for (var i = 0; i &lt; countToTake; ++i)\n        {\n            var next = random.Next(0, internalList.Count - selected.Count);\n            selected.Add(internalList[next]);\n            internalList[next] = internalList[internalList.Count - selected.Count];\n        }\n        return selected;\n    }\n</code></pre>\n'}, {'answer_id': 34190704, 'author': 'Wolf5', 'author_id': 37643, 'author_profile': 'https://Stackoverflow.com/users/37643', 'pm_score': 0, 'selected': False, 'text': '<p>Using LINQ with large lists (when costly to touch each element) AND if you can live with the possibility of duplicates:</p>\n\n<pre><code>new int[5].Select(o =&gt; (int)(rnd.NextDouble() * maxIndex)).Select(i =&gt; YourIEnum.ElementAt(i))\n</code></pre>\n\n<p>For my use i had a list of 100.000 elements, and because of them being pulled from a DB I about halfed (or better) the time compared to a rnd on the whole list.</p>\n\n<p>Having a large list will reduce the odds greatly for duplicates.</p>\n'}, {'answer_id': 34696413, 'author': 'Cardinal', 'author_id': 1180397, 'author_profile': 'https://Stackoverflow.com/users/1180397', 'pm_score': 1, 'selected': False, 'text': '<pre><code>public static IEnumerable&lt;T&gt; GetRandom&lt;T&gt;(IList&lt;T&gt; list, int count, Random random)\n    {\n        // Probably you should throw exception if count &gt; list.Count\n        count = Math.Min(list.Count, count);\n\n        var selectedIndices = new SortedSet&lt;int&gt;();\n\n        // Random upper bound (exclusive)\n        int randomMax = list.Count;\n\n        while (selectedIndices.Count &lt; count)\n        {\n            int randomIndex = random.Next(0, randomMax);\n\n            // skip over already selected indices\n            foreach (var selectedIndex in selectedIndices)\n                if (selectedIndex &lt;= randomIndex)\n                    ++randomIndex;\n                else\n                    break;\n\n            yield return list[randomIndex];\n\n            selectedIndices.Add(randomIndex);\n            --randomMax;\n        }\n    }\n</code></pre>\n<p>Memory: ~count<br>\nComplexity: O(count<sup>2</sup>)</p>\n'}, {'answer_id': 35050572, 'author': 'Dai', 'author_id': 5849502, 'author_profile': 'https://Stackoverflow.com/users/5849502', 'pm_score': -1, 'selected': False, 'text': '<p>When N is very large, the normal method that randomly shuffles the N numbers and selects, say, first k numbers, can be prohibitive because of space complexity. The following algorithm requires only O(k) for both time and space complexities.</p>\n\n<p><a href="http://arxiv.org/abs/1512.00501" rel="nofollow">http://arxiv.org/abs/1512.00501</a></p>\n\n<pre><code>def random_selection_indices(num_samples, N):\n    modified_entries = {}\n    seq = []\n    for n in xrange(num_samples):\n        i = N - n - 1\n        j = random.randrange(i)\n\n        # swap a[j] and a[i] \n        a_j = modified_entries[j] if j in modified_entries else j \n        a_i = modified_entries[i] if i in modified_entries else i\n\n        if a_i != j:\n            modified_entries[j] = a_i   \n        elif j in modified_entries:   # no need to store the modified value if it is the same as index\n            modified_entries.pop(j)\n\n        if a_j != i:\n            modified_entries[i] = a_j \n        elif i in modified_entries:   # no need to store the modified value if it is the same as index\n            modified_entries.pop(i)\n        seq.append(a_j)\n    return seq\n</code></pre>\n'}, {'answer_id': 37836199, 'author': 'Jesús López', 'author_id': 4540020, 'author_profile': 'https://Stackoverflow.com/users/4540020', 'pm_score': 3, 'selected': False, 'text': '<p>Here you have one implementation based on <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow noreferrer">Fisher-Yates Shuffle</a> whose algorithm complexity is O(n) where n is the subset or sample size, instead of the list size, as John Shedletsky pointed out.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; GetRandomSample&lt;T&gt;(this IList&lt;T&gt; list, int sampleSize)\n{\n    if (list == null) throw new ArgumentNullException("list");\n    if (sampleSize &gt; list.Count) throw new ArgumentException("sampleSize may not be greater than list count", "sampleSize");\n    var indices = new Dictionary&lt;int, int&gt;(); int index;\n    var rnd = new Random();\n\n    for (int i = 0; i &lt; sampleSize; i++)\n    {\n        int j = rnd.Next(i, list.Count);\n        if (!indices.TryGetValue(j, out index)) index = j;\n\n        yield return list[index];\n\n        if (!indices.TryGetValue(i, out index)) index = i;\n        indices[j] = index;\n    }\n}\n</code></pre>\n'}, {'answer_id': 51801413, 'author': 'hardsetting', 'author_id': 2779525, 'author_profile': 'https://Stackoverflow.com/users/2779525', 'pm_score': 3, 'selected': False, 'text': "<p>Extending from @ers's answer, if one is worried about possible different implementations of OrderBy, this should be safe:</p>\n\n<pre><code>// Instead of this\nYourList.OrderBy(x =&gt; rnd.Next()).Take(5)\n\n// Temporarily transform \nYourList\n    .Select(v =&gt; new {v, i = rnd.Next()}) // Associate a random index to each entry\n    .OrderBy(x =&gt; x.i).Take(5) // Sort by (at this point fixed) random index \n    .Select(x =&gt; x.v); // Go back to enumerable of entry\n</code></pre>\n"}, {'answer_id': 52261608, 'author': 'Jesse Gador', 'author_id': 10142676, 'author_profile': 'https://Stackoverflow.com/users/10142676', 'pm_score': 1, 'selected': False, 'text': "<p>Goal: Select N number of items from collection source without duplication.\nI created an extension for any generic collection. Here's how I did it:</p>\n\n<pre><code>public static class CollectionExtension\n{\n    public static IList&lt;TSource&gt; RandomizeCollection&lt;TSource&gt;(this IList&lt;TSource&gt; source, int maxItems)\n    {\n        int randomCount = source.Count &gt; maxItems ? maxItems : source.Count;\n        int?[] randomizedIndices = new int?[randomCount];\n        Random random = new Random();\n\n        for (int i = 0; i &lt; randomizedIndices.Length; i++)\n        {\n            int randomResult = -1;\n            while (randomizedIndices.Contains((randomResult = random.Next(0, source.Count))))\n            {\n                //0 -&gt; since all list starts from index 0; source.Count -&gt; maximum number of items that can be randomize\n                //continue looping while the generated random number is already in the list of randomizedIndices\n            }\n\n            randomizedIndices[i] = randomResult;\n        }\n\n        IList&lt;TSource&gt; result = new List&lt;TSource&gt;();\n        foreach (int index in randomizedIndices)\n            result.Add(source.ElementAt(index));\n\n        return result;\n    }\n}\n</code></pre>\n"}, {'answer_id': 62440602, 'author': 'Cyrille', 'author_id': 5974529, 'author_profile': 'https://Stackoverflow.com/users/5974529', 'pm_score': -1, 'selected': False, 'text': '<p>This will solve your issue </p>\n\n<pre><code>var entries=new List&lt;T&gt;();\nvar selectedItems = new List&lt;T&gt;();\n\n\n                for (var i = 0; i !=10; i++)\n                {\n                    var rdm = new Random().Next(entries.Count);\n                        while (selectedItems.Contains(entries[rdm]))\n                            rdm = new Random().Next(entries.Count);\n\n                    selectedItems.Add(entries[rdm]);\n                }\n</code></pre>\n'}, {'answer_id': 63948082, 'author': 'DontPanic345', 'author_id': 3281460, 'author_profile': 'https://Stackoverflow.com/users/3281460', 'pm_score': 3, 'selected': False, 'text': "<p>12 years on and the this question is still active, I didn't find an implementation of Kyle's solution I liked so here it is:</p>\n<pre><code>public IEnumerable&lt;T&gt; TakeRandom&lt;T&gt;(IEnumerable&lt;T&gt; collection, int take)\n{\n    var random = new Random();\n    var available = collection.Count();\n    var needed = take;\n    foreach (var item in collection)\n    {\n        if (random.Next(available) &lt; needed)\n        {\n            needed--;\n            yield return item;\n            if (needed == 0)\n            {\n                break;\n            }\n        }\n        available--;\n    }\n}\n</code></pre>\n"}, {'answer_id': 65986513, 'author': 'Leaky', 'author_id': 2906385, 'author_profile': 'https://Stackoverflow.com/users/2906385', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a benchmark of three different methods:</p>\n<ol>\n<li>The implementation of the accepted answer from <a href="https://stackoverflow.com/users/658/kyle-cronin">Kyle</a>.</li>\n<li>An approach based on random index selection with HashSet duplication filtering, from <a href="https://stackoverflow.com/users/1037948/drzaus">drzaus</a>.</li>\n<li>A more academic approach posted by <a href="https://stackoverflow.com/users/4540020/jes%C3%BAs-l%C3%B3pez">Jesús López</a>, called <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow noreferrer">Fisher–Yates shuffle</a>.</li>\n</ol>\n<p>The testing will consist of benchmarking the performance with multiple different list sizes and selection sizes.</p>\n<p>I also included a <strong>measurement of the standard deviation</strong> of these three methods, i.e. how well distributed the random selection appears to be.</p>\n<p>In a nutshell, <strong><a href="https://stackoverflow.com/users/1037948/drzaus">drzaus</a>\'s simple solution seems to be the best overall</strong>, from these three. The selected answer is great and elegant, but it\'s not that efficient, given that the time complexity is based on the sample size, not the selection size. Consequently, if you select a small number of items from a long list, it will take orders of magnitude more time. Of course it still performs better than the solutions based on complete reordering.</p>\n<p><em>Curiously enough, this <code>O(n)</code> time complexity issue is true even if you only touch the list when you actually return an item, like I do in my implementation. The only thing I can thing of is that <code>Random.Next()</code> is pretty slow, and that performance benefits if you generate only one random number for each selected item.</em></p>\n<p><em>And, also interestingly, the StdDev of Kyle\'s solution was significantly higher comparatively. I have no clue why; maybe the fault is in my implementation.</em></p>\n<p>Sorry for the long code and output that will commence now; but I hope it\'s somewhat illuminative. Also, if you spot any issues in the tests or implementations, let me know and I\'ll fix it.</p>\n<pre class="lang-cs prettyprint-override"><code>static void Main()\n{\n    BenchmarkRunner.Run&lt;Benchmarks&gt;();\n\n    new Benchmarks() { ListSize = 100, SelectionSize = 10 }\n        .BenchmarkStdDev();\n}\n\n[MemoryDiagnoser]\npublic class Benchmarks\n{\n    [Params(50, 500, 5000)]\n    public int ListSize;\n\n    [Params(5, 10, 25, 50)]\n    public int SelectionSize;\n\n    private Random _rnd;\n    private List&lt;int&gt; _list;\n    private int[] _hits;\n\n    [GlobalSetup]\n    public void Setup()\n    {\n        _rnd = new Random(12345);\n        _list = Enumerable.Range(0, ListSize).ToList();\n        _hits = new int[ListSize];\n    }\n\n    [Benchmark]\n    public void Test_IterateSelect()\n        =&gt; Random_IterateSelect(_list, SelectionSize).ToList();\n\n    [Benchmark]\n    public void Test_RandomIndices() \n        =&gt; Random_RandomIdices(_list, SelectionSize).ToList();\n\n    [Benchmark]\n    public void Test_FisherYates() \n        =&gt; Random_FisherYates(_list, SelectionSize).ToList();\n\n    public void BenchmarkStdDev()\n    {\n        RunOnce(Random_IterateSelect, &quot;IterateSelect&quot;);\n        RunOnce(Random_RandomIdices, &quot;RandomIndices&quot;);\n        RunOnce(Random_FisherYates, &quot;FisherYates&quot;);\n\n        void RunOnce(Func&lt;IEnumerable&lt;int&gt;, int, IEnumerable&lt;int&gt;&gt; method, string methodName)\n        {\n            Setup();\n            for (int i = 0; i &lt; 1000000; i++)\n            {\n                var selected = method(_list, SelectionSize).ToList();\n                Debug.Assert(selected.Count() == SelectionSize);\n                foreach (var item in selected) _hits[item]++;\n            }\n            var stdDev = GetStdDev(_hits);\n            Console.WriteLine($&quot;StdDev of {methodName}: {stdDev :n} (% of average: {stdDev / (_hits.Average() / 100) :n})&quot;);\n        }\n\n        double GetStdDev(IEnumerable&lt;int&gt; hits)\n        {\n            var average = hits.Average();\n            return Math.Sqrt(hits.Average(v =&gt; Math.Pow(v - average, 2)));\n        }\n    }\n\n    public IEnumerable&lt;T&gt; Random_IterateSelect&lt;T&gt;(IEnumerable&lt;T&gt; collection, int needed)\n    {\n        var count = collection.Count();\n        for (int i = 0; i &lt; count; i++)\n        {\n            if (_rnd.Next(count - i) &lt; needed)\n            {\n                yield return collection.ElementAt(i);\n                if (--needed == 0)\n                    yield break;\n            }\n        }\n    }\n\n    public IEnumerable&lt;T&gt; Random_RandomIdices&lt;T&gt;(IEnumerable&lt;T&gt; list, int needed)\n    {\n        var selectedItems = new HashSet&lt;T&gt;();\n        var count = list.Count();\n\n        while (needed &gt; 0)\n            if (selectedItems.Add(list.ElementAt(_rnd.Next(count))))\n                needed--;\n\n        return selectedItems;\n    }\n\n    public IEnumerable&lt;T&gt; Random_FisherYates&lt;T&gt;(IEnumerable&lt;T&gt; list, int sampleSize)\n    {\n        var count = list.Count();\n        if (sampleSize &gt; count) throw new ArgumentException(&quot;sampleSize may not be greater than list count&quot;, &quot;sampleSize&quot;);\n        var indices = new Dictionary&lt;int, int&gt;(); int index;\n\n        for (int i = 0; i &lt; sampleSize; i++)\n        {\n            int j = _rnd.Next(i, count);\n            if (!indices.TryGetValue(j, out index)) index = j;\n\n            yield return list.ElementAt(index);\n\n            if (!indices.TryGetValue(i, out index)) index = i;\n            indices[j] = index;\n        }\n    }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>|        Method | ListSize | Select |        Mean |     Error |    StdDev |  Gen 0 | Allocated |\n|-------------- |--------- |------- |------------:|----------:|----------:|-------:|----------:|\n| IterateSelect |       50 |      5 |    711.5 ns |   5.19 ns |   4.85 ns | 0.0305 |     144 B |\n| RandomIndices |       50 |      5 |    341.1 ns |   4.48 ns |   4.19 ns | 0.0644 |     304 B |\n|   FisherYates |       50 |      5 |    573.5 ns |   6.12 ns |   5.72 ns | 0.0944 |     447 B |\n\n| IterateSelect |       50 |     10 |    967.2 ns |   4.64 ns |   3.87 ns | 0.0458 |     220 B |\n| RandomIndices |       50 |     10 |    709.9 ns |  11.27 ns |   9.99 ns | 0.1307 |     621 B |\n|   FisherYates |       50 |     10 |  1,204.4 ns |  10.63 ns |   9.94 ns | 0.1850 |     875 B |\n\n| IterateSelect |       50 |     25 |  1,358.5 ns |   7.97 ns |   6.65 ns | 0.0763 |     361 B |\n| RandomIndices |       50 |     25 |  1,958.1 ns |  15.69 ns |  13.91 ns | 0.2747 |    1298 B |\n|   FisherYates |       50 |     25 |  2,878.9 ns |  31.42 ns |  29.39 ns | 0.3471 |    1653 B |\n\n| IterateSelect |       50 |     50 |  1,739.1 ns |  15.86 ns |  14.06 ns | 0.1316 |     629 B |\n| RandomIndices |       50 |     50 |  8,906.1 ns |  88.92 ns |  74.25 ns | 0.5951 |    2848 B |\n|   FisherYates |       50 |     50 |  4,899.9 ns |  38.10 ns |  33.78 ns | 0.4349 |    2063 B |\n\n| IterateSelect |      500 |      5 |  4,775.3 ns |  46.96 ns |  41.63 ns | 0.0305 |     144 B |\n| RandomIndices |      500 |      5 |    327.8 ns |   2.82 ns |   2.50 ns | 0.0644 |     304 B |\n|   FisherYates |      500 |      5 |    558.5 ns |   7.95 ns |   7.44 ns | 0.0944 |     449 B |\n\n| IterateSelect |      500 |     10 |  5,387.1 ns |  44.57 ns |  41.69 ns | 0.0458 |     220 B |\n| RandomIndices |      500 |     10 |    648.0 ns |   9.12 ns |   8.54 ns | 0.1307 |     621 B |\n|   FisherYates |      500 |     10 |  1,154.6 ns |  13.66 ns |  12.78 ns | 0.1869 |     889 B |\n\n| IterateSelect |      500 |     25 |  6,442.3 ns |  48.90 ns |  40.83 ns | 0.0763 |     361 B |\n| RandomIndices |      500 |     25 |  1,569.6 ns |  15.79 ns |  14.77 ns | 0.2747 |    1298 B |\n|   FisherYates |      500 |     25 |  2,726.1 ns |  25.32 ns |  22.44 ns | 0.3777 |    1795 B |\n\n| IterateSelect |      500 |     50 |  7,775.4 ns |  35.47 ns |  31.45 ns | 0.1221 |     629 B |\n| RandomIndices |      500 |     50 |  2,976.9 ns |  27.11 ns |  24.03 ns | 0.6027 |    2848 B |\n|   FisherYates |      500 |     50 |  5,383.2 ns |  36.49 ns |  32.35 ns | 0.8163 |    3870 B |\n\n| IterateSelect |     5000 |      5 | 45,208.6 ns | 459.92 ns | 430.21 ns |      - |     144 B |\n| RandomIndices |     5000 |      5 |    328.7 ns |   5.15 ns |   4.81 ns | 0.0644 |     304 B |\n|   FisherYates |     5000 |      5 |    556.1 ns |  10.75 ns |  10.05 ns | 0.0944 |     449 B |\n\n| IterateSelect |     5000 |     10 | 49,253.9 ns | 420.26 ns | 393.11 ns |      - |     220 B |\n| RandomIndices |     5000 |     10 |    642.9 ns |   4.95 ns |   4.13 ns | 0.1307 |     621 B |\n|   FisherYates |     5000 |     10 |  1,141.9 ns |  12.81 ns |  11.98 ns | 0.1869 |     889 B |\n\n| IterateSelect |     5000 |     25 | 54,044.4 ns | 208.92 ns | 174.46 ns | 0.0610 |     361 B |\n| RandomIndices |     5000 |     25 |  1,480.5 ns |  11.56 ns |  10.81 ns | 0.2747 |    1298 B |\n|   FisherYates |     5000 |     25 |  2,713.9 ns |  27.31 ns |  24.21 ns | 0.3777 |    1795 B |\n\n| IterateSelect |     5000 |     50 | 54,418.2 ns | 329.62 ns | 308.32 ns | 0.1221 |     629 B |\n| RandomIndices |     5000 |     50 |  2,886.4 ns |  36.53 ns |  34.17 ns | 0.6027 |    2848 B |\n|   FisherYates |     5000 |     50 |  5,347.2 ns |  59.45 ns |  55.61 ns | 0.8163 |    3870 B |\n\nStdDev of IterateSelect: 671.88 (% of average: 0.67)\nStdDev of RandomIndices: 296.07 (% of average: 0.30)\nStdDev of FisherYates: 280.47 (% of average: 0.28)\n</code></pre>\n'}, {'answer_id': 72070751, 'author': 'TXNPRS', 'author_id': 19002336, 'author_profile': 'https://Stackoverflow.com/users/19002336', 'pm_score': 1, 'selected': False, 'text': '<p>Short and simple. Hope this helps someone!</p>\n<pre><code>if (list.Count &gt; maxListCount)\n{\n    var rndList = new List&lt;YourEntity&gt;();\n    var r = new Random();\n    \n    while (rndList.Count &lt; maxListCount)\n    {\n        var addingElement = list[r.Next(list.Count)];\n\n        //element uniqueness checking\n        //choose your case\n        //if (rndList.Contains(addingElement))\n        //if (rndList.Any(p =&gt; p.Id == addingElement.Id))\n            continue;\n    \n        rndList.Add(addingElement);\n    }\n    \n    return rndList;\n}\n</code></pre>\n'}, {'answer_id': 72335120, 'author': 'Kuba Szostak', 'author_id': 2524798, 'author_profile': 'https://Stackoverflow.com/users/2524798', 'pm_score': 1, 'selected': False, 'text': '<pre class="lang-cs prettyprint-override"><code>public static IEnumerable&lt;TItem&gt; RandomSample&lt;TItem&gt;(this IReadOnlyList&lt;TItem&gt; items, int count) \n{\n    if (count &lt; 1 || count &gt; items.Count)\n    {\n        throw new ArgumentOutOfRangeException(nameof(count));\n    }\n    List&lt;int&gt; indexes = Enumerable.Range(0, items.Count).ToList();\n    int yieldedCount = 0;\n\n    while (yieldedCount &lt; count)\n    {\n        int i = RandomNumberGenerator.GetInt32(indexes.Count);\n        int randomIndex = indexes[i];\n        yield return items[randomIndex];\n\n        // indexes.RemoveAt(i);                  // Avoid removing items from the middle of the list\n        indexes[i] = indexes[indexes.Count - 1]; // Replace yielded index with the last one\n        indexes.RemoveAt(indexes.Count - 1);     \n        yieldedCount++;\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/48087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4541/']