分享

C# DataSet转换为List

 修行的嘟嘟 2017-08-31
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Base
{
    public class BaseClass
    {
        //DataSet转换为List
        /// <summary>
        /// DataSet转换为List
        /// </summary>
        /// <typeparam name="T">模板</typeparam>
        /// <param name="dataSet">待转换数据</param>
        /// <returns>转换后数据</returns>
        public static List<T> ConvertToList<T>(DataTable dataTable)
        {
            List<T> buffer = new List<T>();

            // 遍历所有行
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                DataRow row = dataTable.Rows[i];

                T t = Activator.CreateInstance<T>();

                // 遍历所属性
                foreach (System.Reflection.PropertyInfo property in typeof(T).GetProperties())
                {
                    // 该属性包含在集合中
                    if (dataTable.Columns.Contains(property.Name) && !property.Name.Equals("Id"))
                    {
                        // 该属性值不是空
                        if (row[property.Name] != DBNull.Value && row[property.Name] != null)
                        {
                            // 整型
                            if (property.PropertyType.Equals(typeof(int)))
                            {
                                property.SetValue(t, Convert.ToInt32(row[property.Name]), null);
                            }
                            else if (property.PropertyType == typeof(double))
                            {
                                property.SetValue(t, Convert.ToDouble(row[property.Name]), null);
                            }
                            else if (property.PropertyType.Equals(typeof(string)))
                            {
                                property.SetValue(t, row[property.Name].ToString(), null);
                            }
                            else if (property.PropertyType.Equals(typeof(DateTime)))
                            {
                                property.SetValue(t, Convert.ToDateTime(row[property.Name]), null);
                            }
                            else
                            {
                                property.SetValue(t, row[property.Name], null);
                            }
                        }
                    }
                }
                buffer.Add(t);
            }

            return buffer;
        }
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多