软件编程
位置:首页>> 软件编程>> C#编程>> c#中DataTable转List的2种方法示例

c#中DataTable转List的2种方法示例

作者:chenweilong213  发布时间:2022-05-10 20:51:09 

标签:c#,datatable,list

在项目中常常常使用到DataTable,假设DataTable使用得当,不仅能使程序简洁有用,并且可以提高性能,达到事半功倍的效果,List<T>类是ArrayList类的泛型等效类,该类使用大小可按需动态增加的数组实现IList<T>泛型接口。这篇文章主要介绍了c# DataTable 转 List的两种方法,下面来一起看看吧。

1.  直接写一个datatable转list的类

2. 利用泛型来写,更加通用


public List<Dictionary<string, object>> DatatoTable(DataTable dt)
{

List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
   foreach (DataRow dr in dt.Rows)//每一行信息,新建一个Dictionary<string,object>,将该行的每列信息加入到字典
   {
       Dictionary<string, object> result = new Dictionary<string, object>();
       foreach (DataColumn dc in dt.Columns)
       {
           result.Add(dc.ColumnName, dr[dc].ToString());
       }
       list.Add(result);
   }
   return list;
}

public class TabletoList
   {
       public static List<T> TableToListModel<T>(DataTable dt) where T : new()
       {
           // 定义集合    
           List<T> ts = new List<T>();

// 获得此模型的类型  
           Type type = typeof(T);
           string tempName = "";

foreach (DataRow dr in dt.Rows)
           {
               T t = new T();
               // 获得此模型的公共属性      
               PropertyInfo[] propertys = t.GetType().GetProperties();
               foreach (PropertyInfo pi in propertys)
               {
                   tempName = pi.Name;  // 检查DataTable是否包含此列    

if (dt.Columns.Contains(tempName))
                   {
                       // 判断此属性是否有Setter      
                       if (!pi.CanWrite) continue;

object value = dr[tempName];
                       if (value != DBNull.Value)
                           pi.SetValue(t, value, null);
                   }
               }
               ts.Add(t);
           }
           return ts;
       }
   }

第二个方法在使用的时候需要注意:T为自己定义的类,其中的属性需要与数据库对应

来源:https://blog.csdn.net/chenweilong213/article/details/115578126

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com