Ejemplo n.º 1
0
        /// <summary>
        /// happyhippy Extension:将原集合转换为目标集合
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static List <TResult> ConvertTo <TResult>(this IEnumerable source)
            where TResult : new()
        {
            if (source == null) //啥都不用干
            {
                return(null);
            }

            if (source is IEnumerable <TResult> )
            {
                return(source.Cast <TResult>().ToList());//源类型于目标类型一致,可以直接转换
            }
            List <TResult> result            = new List <TResult>();
            bool           hasGetElementType = false;
            IEnumerable <CommonProperty> commonProperties = null; //公共属性(按属性名称进行匹配)

            foreach (var s in source)
            {
                if (!hasGetElementType) //访问第一个元素时,取得属性对应关系;后续的元素就不用再重新计算了
                {
                    if (s is TResult)   //如果源类型是目标类型的子类,可以直接Cast<T>扩展方法
                    {
                        return(source.Cast <TResult>().ToList());
                    }
                    commonProperties  = PropertyCache.GetCommonProperties(s.GetType(), typeof(TResult));
                    hasGetElementType = true;
                }

                TResult t = new TResult();
                foreach (CommonProperty commonProperty in commonProperties) //逐个属性拷贝
                {
                    object value = commonProperty.SourceProperty.GetValue(s, null);
                    commonProperty.TargetProperty.SetValue(t, value, null);
                }
                result.Add(t);
            }

            return(result);
        }