Convert Element type in Collection - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Convert Element type in Collection

Demo Code


using System.Collections.Generic;
using System.Collections;
using System;//from   www .ja va2s  . c  o m

public class Main{
        public static ICollection<T> ConvertCollections<T, V>(ICollection<V> values)
            where T : class
        {
            List<T> result = null;
            result = new List<T>();
            foreach (V val in values)
            {
                if (val is T)
                {
                    result.Add(val as T);
                }
                else
                {
                    throw new InvalidCastException(String.Format("Cannot convert from {0} to {1}", typeof(V).FullName, typeof(T).FullName));
                }
            }
            return (ICollection<T>)result;
        }
}

Related Tutorials