一、List<T>/IEnumerable转换到DataTable/DataView

方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
private DataTable ToDataTable<T>(List<T> items)
{
    var tb = new DataTable(typeof (T).Name);
 
    PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
 
    foreach (PropertyInfo prop in props)
    {
        Type t = GetCoreType(prop.PropertyType);
        tb.Columns.Add(prop.Name, t);
    }
 
    foreach (T item in items)
    {
        var values = new object[props.Length];
 
        for (int i = 0; i < props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }
 
        tb.Rows.Add(values);
    }
 
    return tb;
}
 
/// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
    return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
 
/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
    if (t != null && IsNullable(t))
    {
        if (!t.IsValueType)
        {
            return t;
        }
        else
        {
            return Nullable.GetUnderlyingType(t);
        }
    }
    else
    {
        return t;
    }
}

方法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static DataTable ToDataTable<T>(IEnumerable<T> collection)
 {
     var props = typeof(T).GetProperties();
     var dt = new DataTable();
     dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
     if (collection.Count() > 0)
     {
         for (int i = 0; i < collection.Count(); i++)
         {
             ArrayList tempList = new ArrayList();
             foreach (PropertyInfo pi in props)
             {
                 object obj = pi.GetValue(collection.ElementAt(i), null);
                 tempList.Add(obj);
             }
             object[] array = tempList.ToArray();
             dt.LoadDataRow(array, true);
         }
     }
     return dt;
 }

二、DataTable转换到List

方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public static IList<T> ConvertTo<T>(DataTable table) 
   if (table == null
   
       return null
   
 
   List<DataRow> rows = new List<DataRow>(); 
 
   foreach (DataRow row in table.Rows) 
   
       rows.Add(row); 
   
 
   return ConvertTo<T>(rows); 
 
public static IList<T> ConvertTo<T>(IList<DataRow> rows) 
   IList<T> list = null
 
   if (rows != null
   
       list = new List<T>(); 
 
       foreach (DataRow row in rows) 
       
           T item = CreateItem<T>(row); 
           list.Add(item); 
       
   
 
   return list;
}   
 
public static T CreateItem<T>(DataRow row)   
{
    T obj = default(T);   
    if (row != null)   
    {   
       obj = Activator.CreateInstance<T>();   
 
       foreach (DataColumn column in row.Table.Columns)   
       {   
           PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);   
           try   
           {   
               object value = row[column.ColumnName];   
               prop.SetValue(obj, value, null);   
           }   
           catch   
           //You can log something here    
               //throw;   
           }   
       }   
    }   
 
return obj;   
}

方法二:

把查询结果以DataTable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便。

所以很多人都是按照以下方式做的:

1
2
3
4
// 获得查询结果 
DataTable dt = DbHelper.ExecuteDataTable(...); 
// 把DataTable转换为IList<UserInfo> 
IList<UserInfo> users = ConvertToUserInfo(dt);

问题:如果此系统有几十上百个模型,那不是每个模型中都要写个把DataTable转换为此模型的方法吗?

解决:能不能写个通用类,可以把DataTable转换为任何模型,呵呵,这就需要利用反射和泛型了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;     
using System.Collections.Generic; 
using System.Text;   
using System.Data;   
using System.Reflection; 
namespace NCL.Data   
{   
    /// <summary>   
    /// 实体转换辅助类   
    /// </summary>   
    public class ModelConvertHelper<T> where   T : new()   
     {   
        public static IList<T> ConvertToModel(DataTable dt)   
         {   
            // 定义集合   
             IList<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;    
         }    
     }   
}

使用方式:

1
2
3
4
// 获得查询结果 
DataTable dt = DbHelper.ExecuteDataTable(...); 
// 把DataTable转换为IList<UserInfo> 
IList<UserInfo> users = ModelConvertHelper<UserInfo>.ConvertToModel(dt);

.net core C# DataTable 和List之间相互转换的方法的更多相关文章

  1. C# DataTable 和List之间相互转换的方法

    介绍:List/IEnumerable转换到DataTable/DataView,以及DataTable转换到List 正文: 一.List<T>/IEnumerable转换到DataTa ...

  2. 转 C# DataTable 和List之间相互转换的方法

    一.List/IEnumerable转换到DataTable/DataView 方法一: /// <summary> /// Convert a List{T} to a DataTabl ...

  3. C# DataTable 和List之间相互转换的方法(转载)

    来源:https://www.cnblogs.com/shiyh/p/7478241.html 一.List<T>/IEnumerable转换到DataTable/DataView 方法一 ...

  4. win32内核程序中进程的pid,handle,eprocess之间相互转换的方法

    很有用,收下以后方便查询. 原贴地址:http://bbs.pediy.com/showthread.php?t=119193 在win32内核程序开发中,我们常常需要取得某进程的pid或句柄,或者需 ...

  5. 关于数组和List之间相互转换的方法

    1.List转换成为数组:返回数组的运行时类型.如果列表能放入指定的数组.否则,将根据指定数组.如果指定的数组的元素比列表的多),那么会将存储列表元素的数组. 返回:包含列表元素的list.add(& ...

  6. DOS和UNIX文本文件之间相互转换的方法

    在Unix/Linux下可以使用file命令查看文件类型,如下: file dosfile.txt 使用dos2unix 一般Linux发行版中都带有这个小工具,只能把DOS转换为UNIX文件,命令如 ...

  7. json对象与javaBean,String字符创之间相互转换的方法

    原创:转载请注明出处 package com.allcam.system.utils; import com.fasterxml.jackson.databind.ObjectMapper; publ ...

  8. protobuf与json相互转换的方法

    google的protobuf对象转json,不能直接使用FastJson之类的工具进行转换,原因是protobuf生成对象的get方法,返回的类型有byte[],而只有String类型可以作为jso ...

  9. 路由其实也可以很简单-------Asp.net WebAPI学习笔记(一) ASP.NET WebApi技术从入门到实战演练 C#面向服务WebService从入门到精通 DataTable与List<T>相互转换

    路由其实也可以很简单-------Asp.net WebAPI学习笔记(一)   MVC也好,WebAPI也好,据我所知,有部分人是因为复杂的路由,而不想去学的.曾经见过一位程序猿,在他MVC程序中, ...

  10. IRandomAccessStream, IBuffer, Stream, byte[] 之间相互转换

    /* * 用于实现 IRandomAccessStream, IBuffer, Stream, byte[] 之间相互转换的帮助类 */ using System;using System.IO;us ...

随机推荐

  1. 一个简单的开源消息中间件 FolkMQ v1.4.2 发布

    功能简表 角色 功能 生产者(客户端) 发布消息.定时消息(或叫延时).顺序消息.可过期消息.事务消息.支持 Qos0.Qos1 消费者(客户端) 订阅.取消订阅.消费-ACK(自动.手动) 服务端 ...

  2. SQL case when then end

    SQL case when then end sql中的返回值可以使用case when then end来进行实现 SELECT s.s_id, CASE s.s_name WHEN '1' THE ...

  3. 提质增效,安全灵活,阿里云EDA上云方案让芯片设计驶入高速路

    简介: 今天下午14点,直播间等你 导语:随着芯片工艺的跃升,EDA 需要越来越大的计算能力,处理高达PB级的海量数据.传统的算力交付模式已无法跟上快速发展的芯片设计行业,云的快速交付与强大生态提供了 ...

  4. 阿里云 VPC 内网性能测试最佳实践

    ​简介:本文介绍了在阿里云 VPC 内网执行性能测试的方法.相较于传统的公网性能测试,VPC 内网性能测试完全在客户 VPC 环境进行,无需暴露服务到公网,安全性更高,灵活性更强. 作者:风起 背景 ...

  5. 【ESSD技术解读-04】ESSD Auto PL规格,引领IO性能弹性新方向

    ​简介: 阿里云 ESSD 为云服务器 ECS 提供低时延.持久性和高可靠的块存储服务,成为云厂商全闪块存储的业界标杆.存储团队推出了 ESSD Auto PL 新的云盘规格,把性能与容量解耦,提供 ...

  6. ClickHouse常用Sql

    -- 删除字段 ALTER TABLE 表名 DROP COLUMN 字段名; -- 新增字段,和字段备注 ALTER TABLE 表名 ADD COLUMN IF NOT EXISTS 字段名 St ...

  7. mybatis插件generator使用生成错误问题Execution default-cli of goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.2:generate failed: Exception getting JDBC Driver

    使用插件除了其他回答的路径等问题,我遇到的把jar版本换一下就成了 把5点几的换成8点几的就好使了

  8. linux 下jq的使用

    安装: yum install jq -y 文档: https://stedolan.github.io/jq/manual/ 更多: https://blog.csdn.net/Cheat11730 ...

  9. Deepin安装Python3

    https://www.jianshu.com/p/0c61bdfb9589 也可以看这篇,本文是这篇的简捷版,均原创 首先,把系统更到最新,并复制下面的代码 sudo apt update 更新软件 ...

  10. Nginx在Windows 10、Ubuntu16.04、Centos7下的安装

    目录 一. Windows 10 安装nginx 二. Ubuntu16.04 安装apt nginx 三. Centos7 yum安装nginx 四. ubuntu/centos编译安装nginx ...