DataSet,DataTable转换为list的几个实用方法

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;

namespace Utility
{
    public static class Utility
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
        public static IList<T> ToList<T>(this SqlDataReader reader, bool isNeedCloseDataReader = true) where T : class, new()
        {
            var resultList = new List<T>();
            if (reader != null && !reader.IsClosed)
            {
                int columnLength = 0;
                object data = null;
                while (reader.Read())
                {
                    T entity = new T();
                    var modelType = entity.GetType();
                    if (columnLength == 0)
                        columnLength = reader.FieldCount;

                    for (int i = 0; i < columnLength; i++)
                    {
                        data = reader.GetValue(i);
                        if (data == null || data == DBNull.Value)
                            continue;

                        var modelPropertyInfo = modelType.GetProperty(reader.GetName(i));
                        if (modelPropertyInfo == null)
                            continue;

                        modelPropertyInfo.SetValue(entity, data, modelPropertyInfo.GetIndexParameters());
                    }
                    resultList.Add(entity);
                }

                if (isNeedCloseDataReader)
                {
                    reader.Close();
                    reader.Dispose();
                }
            }
            return resultList;
        }

        public static IList<T> ToList<T>(this DataSet dataSet, int tableIndex) where T : class, new()
        {
            if (dataSet == null || dataSet.Tables.Count < 0) throw new ArgumentNullException("dataSet");

            if (tableIndex > dataSet.Tables.Count - 1) return null;

            if (tableIndex < 0) tableIndex = 0;

            DataTable dataTable = dataSet.Tables[tableIndex];

            // The return value initialization       
            IList<T> resultList = new List<T>();
            for (int j = 0; j < dataTable.Rows.Count; j++)
            {
                T entity = new T();
                PropertyInfo[] propertys = entity.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
                        // Attributes and field names consistent assignment       
                        if (pi.Name.Equals(dataTable.Columns[i].ColumnName))
                        {
                            var val = dataTable.Rows[j][i];
                            if (val == null || val == DBNull.Value)
                                continue;

                            pi.SetValue(entity, val, null);
                            break;
                        }
                    }
                }
                resultList.Add(entity);
            }
            return resultList;
        }

        public static T ToEntity<T>(this DataRow dataRow, string[] columnNames) where T : class, new()
        {
            if (dataRow == null) throw new ArgumentNullException("dataRow");
            if (columnNames == null || columnNames.Length == 0) throw new ArgumentNullException("columnNames");

            T entity = new T();
            PropertyInfo[] propertys = entity.GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                foreach (string columnName in columnNames)
                {
                    // Attributes and field names consistent assignment       
                    if (pi.Name.Equals(columnName))
                    {
                        object val = dataRow[columnName];
                        if (val == DBNull.Value)
                            val = null;

                        pi.SetValue(entity, val, null);
                        break;
                    }
                }
            }
            return entity;
        }

        public static DataTable ToDataTable(this System.Collections.IList list)
        {
            DataTable result = new DataTable();
            Type type = null;

            if (list != null)
            {
                if (list.Count > 0)
                {
                    type = list[0].GetType();
                }
                else
                {
                    Type[] types = list.GetType().GetGenericArguments();
                    if (types.Length > 0)
                    {
                        type = types[0];
                    }
                }
            }
            if (type == null)
            {
                return result;
            }

            PropertyInfo[] propertys = type.GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                Type pt = pi.PropertyType;
                if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
                    pt = Nullable.GetUnderlyingType(pt);
                result.Columns.Add(pi.Name, pt);
            }

            for (int i = 0; i < list.Count; i++)
            {
                ArrayList tempList = new ArrayList();
                foreach (PropertyInfo pi in propertys)
                {
                    object obj = pi.GetValue(list[i], null);
                    tempList.Add(obj);
                }
                object[] array = tempList.ToArray();
                result.LoadDataRow(array, true);
            }
            return result; 
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值