将DataSet转换成List

App.Config配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="GetDataSetConn" connectionString="data source=tong-037;initial catalog=sales;integrated security=true"/>
    
  </connectionStrings>
</configuration>

c#代码块

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Reflection;
using System.Configuration;


namespace DatasetConvertList
{
    //获取数据库连接字符串
    class GetConnStr
    {
        public static string ConnStr()
        {
            string getConn = ConfigurationManager.ConnectionStrings["GetDataSetConn"].ConnectionString;
            return getConn;
        }
    }



    //============================将================================================//




    //首先定义类,类下面的属性成员用来接收从table表里取出的对应字段
    public class UserInfo
    {
        public int ID { get; set; }
        public int Age { get; set; }
        public string Nanme { get; set; }
    }

    class DataTableTolist
    {
        /// <summary>
        ///  获取List<UserInfo>泛型集合   其实也就是//将DataTable转化成list<T> where T:class
        /// </summary>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="sql">sqL语句</param>
        /// <param name="parameter">sql语句的参数</param>
        /// <returns>返回一个list</returns>
        public IList<UserInfo> GetUserInfoAll( string sql, params SqlParameter[] parameter) //定义一个返回值是list<Userinfo>的方法,
        {

            using (SqlConnection conn = new SqlConnection(GetConnStr.ConnStr()))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    foreach (SqlParameter p in parameter)
                    {
                        cmd.Parameters.Add(p);
                    }

                    IList<UserInfo> list = new List<UserInfo>();//定义一个list 到时候用来存放【已经将table表字段转换成Userinfo类属性成员的】类,也就是说list的成员就是Userinfo类的实例,而Userinfo的成员其实就是table表的字段

                    //using (SqlDataAdapter dapter=new SqlDataAdapter (cmd))
                    //{
                    //    dapter.Fill(list);
                    //}
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        UserInfo userinto = new UserInfo(); //实例化一个UserInof类
                        userinto.ID = (int)dr["id"];    //将table表的id字段赋值给UserInof类的ID属性
                        userinto.Age = (int)dr["age"];  //将table表的age字段赋值给UserInof类的Age属性
                        userinto.Nanme = (string)dr["name"]; //将table表的name字段赋值给UserInof类的Nanme属性

                        list.Add(userinto);  //将UserInof类是实例userinfo添加到list中
                    }
                    return list;  //再把这个list返回去
                }
            }

        }
    }





    //========================下面是将一个DataSet转换成一个list=========================//

    //首先定义类,类下面的属性成员用来接收从DataSet里的Table表里取出的对应字段,这也就是一个映射的过程
    public class TabName
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }


    class Program
    {
        /// <summary>
        /// 获取泛型集合,注意,指所有的类型的list哦。【不像上面已经指定了List<T>的类型是UserInfo了哦】
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="sql">sql语句</param>
        /// <param name="parameter">sql语句的参数</param>
        /// <returns>为什么这个方法的返回值是IList<T>呢?那是因为既然是将DataSet转换成list所以我就返回一个list</returns>
        
        public List<T> GetList<T>(string sql, params SqlParameter[] parameter)
        {
            using (SqlConnection conn = new SqlConnection(GetConnStr.ConnStr()))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    foreach (SqlParameter par in parameter)
                    {
                        cmd.Parameters.Add(par);
                    }

                    DataSet ds = new DataSet();

                    //SqlDataAdapter 是 DataSet 和 SQL Server 之间的桥接器,用于检索和保存数据,也就是说SqlDataAdapter通过cmd对象执行的sql命令,获取数据库中的数据,将获取到是数据保存到dapter中,然后用于填充DataSet
                    using (SqlDataAdapter dapter = new SqlDataAdapter(cmd))
                    {
                        //dapter.SelectCommand = cmd;
                        dapter.Fill(ds);

                        return DataSetToList<T>(ds, 0);//调用下面的DataSetToList方法将DataSet转换为List

                    }

                }

            }
        }



        /// <summary>
        /// DataSetToList
        /// </summary>
        /// <typeparam name="T">转换类型</typeparam>
        /// <param name="ds">一个DataSet实例,也就是数据源</param>
        /// <param name="tableIndext">DataSet容器里table的下标,只有用于取得哪个table,也就是需要转换表的索引</param>
        /// <returns></returns>
        public List<T> DataSetToList<T>(DataSet ds, int tableIndext)
        {
            //确认参数有效
            if (ds == null || ds.Tables.Count <= 0 || tableIndext < 0)
            {
                return null;
            }
            DataTable dt = ds.Tables[tableIndext]; //取得DataSet里的一个下标为tableIndext的表,然后赋给dt

            IList<T> list = new List<T>();  //实例化一个list
            // 在这里写 获取T类型的所有公有属性。 注意这里仅仅是获取T类型的公有属性,不是公有方法,也不是公有字段,当然也不是私有属性                                               
            PropertyInfo[] tMembersAll = typeof(T).GetProperties();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象。为什么这里要创建一个泛型对象呢?是因为目前我不确定泛型的类型。
                T t = Activator.CreateInstance<T>();


                //获取t对象类型的所有公有属性。但是我不建议吧这条语句写在for循环里,因为没循环一次就要获取一次,占用资源,所以建议写在外面
                //PropertyInfo[] tMembersAll = t.GetType().GetProperties();


                for (int j = 0; j < dt.Columns.Count; j++) 
                {
                    //遍历tMembersAll
                    foreach (PropertyInfo tMember in tMembersAll)
                    {
                        //取dt表中j列的名字,并把名字转换成大写的字母。整条代码的意思是:如果列名和属性名称相同时赋值
                        if (dt.Columns[j].ColumnName.ToUpper().Equals(tMember.Name.ToUpper()))
                        {
                            //dt.Rows[i][j]表示取dt表里的第i行的第j列;DBNull是指数据库中当一个字段没有被设置值的时候的值,相当于数据库中的“空值”。 
                            if (dt.Rows[i][j] != DBNull.Value)
                            {
                                //SetValue是指:将指定属性设置为指定值。 tMember是T泛型对象t的一个公有成员,整条代码的意思就是:将dt.Rows[i][j]赋值给t对象的tMember成员,参数详情请参照http://msdn.microsoft.com/zh-cn/library/3z2t396t(v=vs.100).aspx/html

                                tMember.SetValue(t, dt.Rows[i][j], null);


                            }
                            else
                            {
                                tMember.SetValue(t, null, null);
                            }
                            break;//注意这里的break是写在if语句里面的,意思就是说如果列名和属性名称相同并且已经赋值了,那么我就跳出foreach循环,进行j+1的下次循环
                        }
                    }
                }

                list.Add(t);
            }
            return list.ToList();

        }



        //我在数据库里建了一个T_user表,里面有三个字段,自增的ID,age,name
        static void Main(string[] args)
        {

            Program p = new Program();
            List<TabName> list = p.GetList<TabName>("select * from T_user where id<=@id", new SqlParameter("id", 3));
            foreach (var s in list)
            {
                Console.WriteLine(s.ID);
                Console.WriteLine(s.Age);
                Console.WriteLine(s.Name);
            }
            Console.ReadKey();
        }
    }
    
}




  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值