木子冬
程序就是规范流程下的替代品,互联网就是对应需求下的一个产业链!

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
统计
 
复制代码
 1   public class ModelConvertHelper<T> where T : new()
 2     {
 3 
 4         /// <summary>
 5         /// Convert To Model
 6         /// </summary>
 7         /// <param name="dt">Datatable for convert</param>
 8         /// <returns>Collection of model</returns>
 9         public static IList<T> ConvertToModel(DataTable dt)
10         {
11             // Collection definition
12             IList<T> ts = new List<T>();
13 
14             // Get model type
15             Type type = typeof(T);
16 
17             string tempName = "";
18 
19             foreach (DataRow dr in dt.Rows)
20             {
21                 T t = new T();
22 
23                 // Get property of model
24                 PropertyInfo[] propertys = t.GetType().GetProperties();
25 
26                 foreach (PropertyInfo pi in propertys)
27                 {
28                     tempName = pi.Name;
29 
30                     // check column is exsit
31                     if (dt.Columns.Contains(tempName))
32                     {
33                         // Whether can be set value
34                         if (!pi.CanWrite) continue;
35 
36                         object value = dr[tempName];
37                         if (value != DBNull.Value)
38                         {
39                             try
40                             {
41                                 pi.SetValue(t, value, null);
42                             }
43                             catch (Exception)
44                             {
45                                 pi.SetValue(t, value.ToString(), null);
46                             }
47                         }
48                     }
49                 }
50 
51                 ts.Add(t);
52             }
53 
54             return ts;
55         }
56 
57     }
复制代码

 

posted on   木子_冬  阅读(303)  评论(0编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· Ollama系列05:Ollama API 使用指南
· 为什么AI教师难以实现
 
点击右上角即可分享
微信分享提示