a better way to cast unknown IEnumerable to typed list - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

a better way to cast unknown IEnumerable to typed list

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections;
using System;/*from   ww w  .  jav  a 2s .  c  om*/

public class Main{
        /// <summary>
        /// a better way to cast unknown IEnumerable to typed list
        /// </summary>
        public static List<T> CastToList<T>(this IEnumerable source)
        {
            var list = new List<T>();
            if (source != null)
            {
                foreach (T item in source)
                {
                    list.Add(item);
                }
            }

            return list;
        }
}

Related Tutorials