Convert a non-generic collection to an array – my most useful extension method ever…

Funny how things work out… I wrote one of my most simple extension methods years ago, one that converts a non-generic collection to an array (because arrays implement IEnumerable<T> on which I can call Linq extension methods).

Lately I find I’ve been using this all the time. This:

using System.Collections;

namespace Example
{
    public static class Extensions
    {
        /// <summary>Converts a non-generic collection to an array.</summary>
        public static T[] ToArray<T>(this ICollection collection)
        {
            var items = new T[collection.Count];
            collection.CopyTo(items, 0);

            return items;
        }
    }
}

An example where this becomes useful is this… Say you have an in-memory dataset in the form of a table, called “table” for want of a better name, containing some rows, and one of the columns is an amount field. If you wanted the sum of the amount, you could just do this:

            var rows = table.Rows.ToArray<DataRow>();
            var total = rows.Sum(r => (double)r["Amount"]);
Advertisements

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged , , . Bookmark the permalink.

2 Responses to Convert a non-generic collection to an array – my most useful extension method ever…

  1. Jose A Terroba says:

    I’m nitpicking, and don’t want to take away from your contribution, but DataTable already has an extension method to make it enumerable. [tbl.AsEnumerable()] and you can do anything with its rows you could with any other IEnumerable.

    Liked by 1 person

    • Jerome says:

      Never heard of that one. 🙂

      And maybe that was a bad example. I’ve used the extension in Winforms when working with Controls and other collections. The point of it was to make an enumeration out of any non-generic collection. Been a while though.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s