Monday, February 8, 2010

Implementing Join() for Arrays in C# Using Extension Methods

Microsoft seems pretty good at borrowing good ideas from others, so why is it that .NET still doesn't include a Join() method for IEnumerables? Luckily it's easy to add this functionality using extension methods. Here is a fairly simple implementation.
using System;
using System.Collections;
using System.Text;
using System.Collections.Generic;

namespace Helpers
{
    public static class CollectionHelper
    {
        public static string Join(this IEnumerable list, string separator)
        {
            string text = "";

            if (null == list)
                return text;

            foreach (object item in list)
            {
                text += String.Format(
                    "{0}{1}", item.ToString(), separator);
            }

            int idx = text.LastIndexOf(separator);
            if (-1 < idx)
            {
                text = text.Remove(text.LastIndexOf(separator));
            }

            return text;
        }
    }
}
You can include the Join() method by adding a using Helpers.CollectionHelpers statement to your source file. It looks something like this.
using System;
using System.Collections;

namespace MyAppSpace
{
    using Helpers.CollectionHelper;

    public partial class SomeClass
    {
        ...

        ...

        public string ProcessData(IList<double> data)
        {
            List<double> new_data = new List<double>();

            double value = 0;
            foreach (double d in data)
            {
                value += d
                new_data.Add(value);
            }

            return new_data.Join(','); // <= Extension method
        }
    }
}

No comments:

Post a Comment