{"id":429,"date":"2019-06-07T13:13:49","date_gmt":"2019-06-07T03:13:49","guid":{"rendered":"http:\/\/www.nerdhold.com\/coder\/?p=429"},"modified":"2019-06-07T20:39:25","modified_gmt":"2019-06-07T10:39:25","slug":"new-linq-method-torandomcollectiontype","status":"publish","type":"post","link":"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/","title":{"rendered":"New LINQ Method: ToRandomCollectionType<>()"},"content":{"rendered":"<p>If you&#8217;ve spent time in the C# world, you&#8217;ve probably encountered (and possibly asked) the question: &#8220;Should I use .ToList() or .ToArray()?&#8221;<\/p>\n<p>The answer, of course, is that it&#8217;s a false dichotomy: I&#8217;ve written before about how you should <a title=\"LINQ and time complexity and data structures, oh my!\" href=\"http:\/\/www.nerdhold.com\/coder\/2014\/11\/25\/linq-and-time-complexity\/\">pick the right data structure for the job<\/a>. But what if you really don&#8217;t care? What if you&#8217;d prefer to just roll the dice and let the computer pick for you? Is that possible?<\/p>\n<p>Of course it is. First, we need an extension method:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic static class Extensions {\r\n    public static IEnumerable&lt;T&gt; ToRandomCollectionType&lt;T&gt;(this IEnumerable&lt;T&gt; collection) {\r\n        throw new NotImplementedException();\r\n    }\r\n}\r\n<\/pre>\n<p>The first thing that&#8217;s going to have to do is pick a collection type. Let&#8217;s load all of the types we can find which implement IEnumerable:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar types = AppDomain.CurrentDomain.GetAssemblies()\r\n                     .SelectMany(assembly =&gt; assembly.GetTypes())\r\n                     .Where(t =&gt; typeof(IEnumerable).IsAssignableFrom(t))\r\n<\/pre>\n<p>We actually want to be pickier than that &#8211; because we need to work out how to actually instantiate one of these types. So let&#8217;s make sure all of our candidate types have a constructor which accepts a single IEnumerable of the passed-in collection type:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n \u00a0\u00a0 \u00a0\u00a0\u00a0 \u00a0\u00a0        \u00a0\u00a0 .Select(t =&gt; { try { return t.MakeGenericType(typeof(T)); } catch { return null; }})\r\n                     .Where(t =&gt; t != null &amp;&amp; t.GetConstructor(constructorParamTypeArray) != null)\r\n<\/pre>\n<p>The try\/catch block there is to deal with classes like ConcurrentDictionary, which require multiple generic parameters even though they implement IEnumerable. Is there a better way to check? Probably! But we&#8217;re not writing production-grade code here, because .ToRandomCollectionType&lt;&gt;() is fundamentally production-unsuitable anyway.<\/p>\n<p>The next step is to randomly select one of our candidate types and grab a reference to the right constructor.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar type = types&#x5B;_rnd.Next(0, types.Count-1)];\r\nvar constructor = type.GetConstructor(constructorParamTypeArray);\r\n<\/pre>\n<p>Now all that&#8217;s left is to invoke the constructor and return the result!<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nreturn (IEnumerable&lt;T&gt;)constructor.Invoke(new &#x5B;] {collection});\r\n<\/pre>\n<p>Does it work? Absolutely! Most of the time, anyway. Here&#8217;s the outcome of feeding { 1, 2, 3 } into it a few times:<\/p>\n<p><a href=\"http:\/\/www.nerdhold.com\/coder\/files\/2019\/06\/ToRandomCollectionType.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-445\" alt=\"ToRandomCollectionType\" src=\"http:\/\/www.nerdhold.com\/coder\/files\/2019\/06\/ToRandomCollectionType-217x300.png\" width=\"217\" height=\"300\" srcset=\"http:\/\/www.nerdhold.com\/coder\/files\/2019\/06\/ToRandomCollectionType-217x300.png 217w, http:\/\/www.nerdhold.com\/coder\/files\/2019\/06\/ToRandomCollectionType.png 628w\" sizes=\"(max-width: 217px) 100vw, 217px\" \/><\/a><\/p>\n<p>Much like the <a title=\"Hooking (Hacking?) the ASP.Net FileChangeNotifier\" href=\"http:\/\/www.nerdhold.com\/coder\/2018\/01\/11\/hooking-hacking-asp-net-filechangenotifier\/\">FileChangeMonitor hack I blogged about<\/a>, this is unsuitable for anything production-like. Please treat it as the humourous hack it is and don&#8217;t use it for anything important!<\/p>\n<p>Hang on though, we&#8217;re not done. You should always test your code. Like, with automated tests.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class ItShouldUsuallyWork\r\n{\r\n    &#x5B;Test]\r\n    public void TryingAFewTimes_SometimesWorks() {\r\n        var inputSet = new List&lt;int&gt; {1, 2, 3};\r\n        int successCount = 0;\r\n        for (int i = 0; i &lt; 10; i++) {\r\n            var result = inputSet.ToRandomCollectionType();\r\n            try {\r\n                inputSet.Should().BeEquivalentTo(result);\r\n                Console.WriteLine($&quot;Got a {result.GetType()}&quot;);\r\n                successCount++;\r\n            }\r\n            catch {\r\n                Console.WriteLine(&quot;Looks like that one failed.&quot;);\r\n            }\r\n        }\r\n        successCount.Should().BeGreaterOrEqualTo(5);\r\n    }\r\n}\r\n<\/pre>\n<p>The <a href=\"https:\/\/github.com\/Rophuine\/ToRandomCollectionType\">code is available on GitHub<\/a>, and there is a <a href=\"https:\/\/www.nuget.org\/packages\/ToRandomCollectionType\">NuGet package<\/a> so this lovely little extension method is never more than a quick &#8220;Install-Package ToRandomCollectionType&#8221; away.<\/p>\n<p>If you enjoy a little C# whimsy, you might like to read about <a title=\"Object.Extend in C# for exploratory coding\" href=\"http:\/\/www.nerdhold.com\/coder\/2018\/04\/09\/object-extend-linqpad\/\">my Object.Extend(&#8230;) implementation in C#<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you&#8217;ve spent time in the C# world, you&#8217;ve probably encountered (and possibly asked) the question: &#8220;Should I use .ToList() or .ToArray()?&#8221; The answer, of course, is that it&#8217;s a false dichotomy: I&#8217;ve written before about how you should pick the right data structure for the job. But what if you really don&#8217;t care? What &hellip; <a href=\"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">New LINQ Method: ToRandomCollectionType<>()<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[18,13,17,12],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>New LINQ Method: ToRandomCollectionType() - Nerdhold Coder<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"New LINQ Method: ToRandomCollectionType() - Nerdhold Coder\" \/>\n<meta property=\"og:description\" content=\"If you&#8217;ve spent time in the C# world, you&#8217;ve probably encountered (and possibly asked) the question: &#8220;Should I use .ToList() or .ToArray()?&#8221; The answer, of course, is that it&#8217;s a false dichotomy: I&#8217;ve written before about how you should pick the right data structure for the job. But what if you really don&#8217;t care? What &hellip; Continue reading New LINQ Method: ToRandomCollectionType() &rarr;\" \/>\n<meta property=\"og:url\" content=\"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/\" \/>\n<meta property=\"og:site_name\" content=\"Nerdhold Coder\" \/>\n<meta property=\"article:published_time\" content=\"2019-06-07T03:13:49+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-06-07T10:39:25+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.nerdhold.com\/coder\/files\/2019\/06\/ToRandomCollectionType-217x300.png\" \/>\n<meta name=\"author\" content=\"Lionell Pack\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Lionell Pack\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/\",\"url\":\"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/\",\"name\":\"New LINQ Method: ToRandomCollectionType() - Nerdhold Coder\",\"isPartOf\":{\"@id\":\"http:\/\/www.nerdhold.com\/coder\/#website\"},\"datePublished\":\"2019-06-07T03:13:49+00:00\",\"dateModified\":\"2019-06-07T10:39:25+00:00\",\"author\":{\"@id\":\"http:\/\/www.nerdhold.com\/coder\/#\/schema\/person\/ca2988d5c0cb756a846e4d8c54e86b77\"},\"breadcrumb\":{\"@id\":\"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/www.nerdhold.com\/coder\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"New LINQ Method: ToRandomCollectionType()\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/www.nerdhold.com\/coder\/#website\",\"url\":\"http:\/\/www.nerdhold.com\/coder\/\",\"name\":\"Nerdhold Coder\",\"description\":\"Tinkerings of a C# Coder\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/www.nerdhold.com\/coder\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"http:\/\/www.nerdhold.com\/coder\/#\/schema\/person\/ca2988d5c0cb756a846e4d8c54e86b77\",\"name\":\"Lionell Pack\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/www.nerdhold.com\/coder\/#\/schema\/person\/image\/\",\"url\":\"http:\/\/0.gravatar.com\/avatar\/9be7b23cd97814ac4a40b9b4d2955b5a?s=96&d=mm&r=pg\",\"contentUrl\":\"http:\/\/0.gravatar.com\/avatar\/9be7b23cd97814ac4a40b9b4d2955b5a?s=96&d=mm&r=pg\",\"caption\":\"Lionell Pack\"},\"sameAs\":[\"http:\/\/blog.rophuine.net\"],\"url\":\"http:\/\/www.nerdhold.com\/coder\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"New LINQ Method: ToRandomCollectionType() - Nerdhold Coder","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/","og_locale":"en_US","og_type":"article","og_title":"New LINQ Method: ToRandomCollectionType() - Nerdhold Coder","og_description":"If you&#8217;ve spent time in the C# world, you&#8217;ve probably encountered (and possibly asked) the question: &#8220;Should I use .ToList() or .ToArray()?&#8221; The answer, of course, is that it&#8217;s a false dichotomy: I&#8217;ve written before about how you should pick the right data structure for the job. But what if you really don&#8217;t care? What &hellip; Continue reading New LINQ Method: ToRandomCollectionType() &rarr;","og_url":"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/","og_site_name":"Nerdhold Coder","article_published_time":"2019-06-07T03:13:49+00:00","article_modified_time":"2019-06-07T10:39:25+00:00","og_image":[{"url":"http:\/\/www.nerdhold.com\/coder\/files\/2019\/06\/ToRandomCollectionType-217x300.png"}],"author":"Lionell Pack","twitter_misc":{"Written by":"Lionell Pack","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/","url":"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/","name":"New LINQ Method: ToRandomCollectionType() - Nerdhold Coder","isPartOf":{"@id":"http:\/\/www.nerdhold.com\/coder\/#website"},"datePublished":"2019-06-07T03:13:49+00:00","dateModified":"2019-06-07T10:39:25+00:00","author":{"@id":"http:\/\/www.nerdhold.com\/coder\/#\/schema\/person\/ca2988d5c0cb756a846e4d8c54e86b77"},"breadcrumb":{"@id":"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/"]}]},{"@type":"BreadcrumbList","@id":"http:\/\/www.nerdhold.com\/coder\/2019\/06\/07\/new-linq-method-torandomcollectiontype\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/www.nerdhold.com\/coder\/"},{"@type":"ListItem","position":2,"name":"New LINQ Method: ToRandomCollectionType()"}]},{"@type":"WebSite","@id":"http:\/\/www.nerdhold.com\/coder\/#website","url":"http:\/\/www.nerdhold.com\/coder\/","name":"Nerdhold Coder","description":"Tinkerings of a C# Coder","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/www.nerdhold.com\/coder\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"http:\/\/www.nerdhold.com\/coder\/#\/schema\/person\/ca2988d5c0cb756a846e4d8c54e86b77","name":"Lionell Pack","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/www.nerdhold.com\/coder\/#\/schema\/person\/image\/","url":"http:\/\/0.gravatar.com\/avatar\/9be7b23cd97814ac4a40b9b4d2955b5a?s=96&d=mm&r=pg","contentUrl":"http:\/\/0.gravatar.com\/avatar\/9be7b23cd97814ac4a40b9b4d2955b5a?s=96&d=mm&r=pg","caption":"Lionell Pack"},"sameAs":["http:\/\/blog.rophuine.net"],"url":"http:\/\/www.nerdhold.com\/coder\/author\/admin\/"}]}},"_links":{"self":[{"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/posts\/429"}],"collection":[{"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/comments?post=429"}],"version-history":[{"count":25,"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/posts\/429\/revisions"}],"predecessor-version":[{"id":461,"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/posts\/429\/revisions\/461"}],"wp:attachment":[{"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/media?parent=429"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/categories?post=429"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.nerdhold.com\/coder\/wp-json\/wp\/v2\/tags?post=429"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}