Quantcast
Viewing all articles
Browse latest Browse all 40

Quick way to convert a Collection to Array or List?

For every *Collection (HtmlNodeCollection, TreeNodeCollection, CookieCollection etc) class instance that I need to pass to a method which accepts only an array or list (shouldn't have a method that accepts a TreeNodeCollection in the TreeView for example?) I have to write a extension-method like this:

public static TreeNode[] ToArray(this TreeNodeCollection nodes)        {            TreeNode[] arr = new TreeNode[nodes.Count];            nodes.CopyTo(arr, 0);            return arr;        }

Or loop over the entire collection adding the items to a output-list and then converting the output-list to an array:

 public static TreeNode[] ToArray(this TreeNodeCollection nodes)        {      var output = new List<TreeNode>();            foreach (TreeNode node in nodes)                output.Nodes(node);            return output.ToArray(); }

So, my question is:I need this extension-methods often. It may allocate a lot of memory if the list are large, as are usually. Why can't I just get a reference (not copy) to the internal array used by this *Collection classes so that I had no need to use that extensions and perfom this memory allocations? or even provide a ToArray() method. We don't need to know its internal implementation or array used in that last case.


Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>