Showing posts with label Extension methods. Show all posts
Showing posts with label Extension methods. Show all posts

Friday, October 5, 2012

Extension class for IEnumerable( Of T)

public static class IEnumerableExtensions
    {
        /// 
        /// ForEach extension method for IEnumerable(Of T)
        /// 
        /// The element type of the IEnumerable object
        /// The IEnumerable(Of T) source
        /// The delegate to perform on each element of the IEnumerable(Of T)
        public static void ForEach(this IEnumerable source, Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            foreach (T item in source)
            {
                action(item);
            }
        }

        /// 
        /// Converts an IEnumerable(Of T) to a delimited string
        /// 
        /// The element type of the IEnumerable object
        /// The IEnumerable(Of T) object
        /// The delimiter to be used in the output string
        /// Delimited string representation of the items
        /// Null or empty items are ignored
        public static string ToDelimitedString(this IEnumerable items, string separator)
        {
            if (items == null || items.Count() == 0)
            {
                return string.Empty;
            }

            return string.Join(separator, items.Where(i => i != null && !i.ToString().IsNullOrWhiteSpace()));
        }

        /// 
        /// Converts an IEnumerable(Of T) to a comma-delimited string
        /// 
        /// The element type of the IEnumerable object
        /// The IEnumerable(Of T) object
        /// Comma-delimited string representation of the items
        /// Null or empty items are ignored
        public static string ToSpaceDelimitedString(this IEnumerable items)
        {
            return items.ToDelimitedString(" ");
        }

        /// 
        /// Converts an IEnumerable(Of T) to a space-delimited string
        /// 
        /// The element type of the IEnumerable object
        /// The IEnumerable(Of T) object
        /// Space-delimited string representation of the items
        /// Null or empty items are ignored
        public static string ToCommaDelimitedString(this IEnumerable items)
        {
            return items.ToDelimitedString(",");
        }
    }