Tuesday, 17 January 2012

Useful IEnumerable Extensions

    ///

    /// Extension methods for IEnumerable
    ///

    public static class IEnumerableExtensions
    {
        ///
        /// Splits a list into list of buckets
        ///

        /// Type
        /// values
        /// Bucket size
        /// List of buckets
        public static IEnumerable> Split(this IEnumerable values, int chunkSize)
        {
            if (chunkSize <= 0)
            {
                throw new ArgumentException("chunkSize should be greater than zero");
            }

            if (values.IsNullOrEmpty())
            {
                throw new ArgumentException("value is either empty or null to Split");
            }

            while (values.Any())
            {
                yield return values.Take(chunkSize);
                values = values.Skip(chunkSize);
            }
        }

        ///
        /// Converts IEnumerable intp CSV
        ///

        /// Type
        /// values
        /// CSV
        public static String ToCSV(this IEnumerable values)
        {
            const string comma = ",";

            if (values.IsNullOrEmpty())
            {
                throw new ArgumentException("value is either empty or null");
            }

            return String.Join(comma, values.ToStrings().ToArray());
        }

        ///
        /// Converts IEnumerable<T> to IEnumerable<String>
        ///

        /// Type
        /// values
        /// IEnumerable<String>
        public static IEnumerable ToStrings(this IEnumerable values)
        {
            if (values.IsNullOrEmpty())
            {
                throw new ArgumentException("value is either empty or null");
            }

            foreach(var value in values)
            {
                yield return value.ToString();
            }
        }

        ///
        /// checks if the list contains any elements
        ///

        /// Type
        /// values
        /// true if not null and contains atleast one element, else false
        public static bool IsNullOrEmpty(this IEnumerable values)
        {
            if (values.IsNull() || values.Count() == 0)
            {
                return true;
            }

            return false;
        }
    }

No comments: