Dynamically converts an IEnumerable to a generic list based on the given type. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Dynamically converts an IEnumerable to a generic list based on the given type.

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;//w w w.j  ava 2 s. co  m

public class Main{
        /// <summary>
      /// Dynamically converts an IEnumerable to a generic list based on the given type.
      /// </summary>
      /// <remarks>
      /// This method is suitable when the <param name="type">type</param> parameter's value is determined at runtime.
      /// </remarks>
      /// <example>
      /// foreach (var group in Model.GroupBy(item=>item.GetType()))
       /// {
       ///     Html.RenderPartial(string.Format("GeoObjectView/Structure/{0}s", group.Key.Name), group.AsListOf(group.Key));
       /// }
      /// </example>
      public static IList AsListOf(this IEnumerable coll, Type type)
      {
            var result = (IList) typeof (List<>).MakeGenericType(type).GetConstructor(Type.EmptyTypes).Invoke(null);
         foreach (var item in coll) result.Add(item);
         return result;
      }
        public static List<T> Add<T>(this List<T> list, params T[] items)
      {
         list.AddRange(items);
         return list;
      }
}

Related Tutorials