yangle
2023-09-08 6775b696de3ecbdea4201c6dd57103e165ccb7f8
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebAPI.Utility;
 
namespace WebAPI.Controllers.SCGL.日计划管理
{
    public static class DataHelper
    {
        public static List<T> ToModelList<T>(this DataSet ds) where T : new()
        {
            try
            {
                List<T> list = new List<T>();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        list.Add(row.Put(new T()));
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
 
        public static List<T> ToModelList<T>(this DataTable dt) where T : new()
        {
            try
            {
                List<T> list = new List<T>();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        list.Add(row.Put(new T()));
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
 
        /// <summary>
        /// 返回一条数据的Model
        /// </summary>
        /// <typeparam name="T">Model类型</typeparam>
        /// <param name="entity">Model类型</param>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static T ToModel<T>(DataSet ds) where T : new()
        {
            try
            {
                T m = new T();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    m = ds.Tables[0].Rows[0].Put(new T());
                }
                return m;
            }
            catch (Exception)
            {
                return default(T);
                //throw;
            }
        }
 
        public static T Put<T>(this DataRow row, T entity) where T : new()
        {
            if (entity == null)
            {
                entity = new T();
            }
            Type type = typeof(T);
            PropertyInfo[] pi = type.GetProperties();
            foreach (PropertyInfo item in pi)
            {
                int index = row.Table.Columns.IndexOf(item.Name);
                if (index != -1)
                {
                    if (row[item.Name] != null && row[item.Name] != DBNull.Value)
                    {
                        if (item.PropertyType == typeof(DateTime))
                        {
                            //如果对日期格式有特殊要求 可以在这里转换
                            item.SetValue(entity, Convert.ToDateTime(row[item.Name].ToString()), null);
                        }
                        else
                        {
                            item.SetValue(entity, ChangeType(row[item.Name], item.PropertyType), null);
                        }
                    }
                }
            }
            return entity;
        }
 
        public static object ChangeType(object obj, Type conversionType)
        {
            return ChangeType(obj, conversionType, Thread.CurrentThread.CurrentCulture);
        }
 
        public static object ChangeType(object obj, Type conversionType, IFormatProvider provider)
        {
 
            #region Nullable
            Type nullableType = Nullable.GetUnderlyingType(conversionType);
            if (nullableType != null)
            {
                if (obj == null)
                {
                    return null;
                }
                return Convert.ChangeType(obj, nullableType, provider);
            }
            #endregion
            if (typeof(System.Enum).IsAssignableFrom(conversionType))
            {
                return Enum.Parse(conversionType, obj.ToString());
            }
            return Convert.ChangeType(obj, conversionType, provider);
        }
 
 
 
        public static string ToListParam<T>(this List<T> list)
        {
            string str = string.Empty;
            foreach (var item in list)
            {
                str += $"'{item}',";
            }
            str = str.TrimEnd(',');
            str = $"({str})";
            return str;
        }
 
 
        public static string GetUpdateStr(string table, Dictionary<string, object> dic, string condition)
        {
            var strSet = string.Empty;
            foreach (var item in dic)
            {
                var type = Util.GetObjectType(item.Value);
                switch (type)
                {
                    case "string":
                    case "date":
                        strSet += $" {item.Key}='{item.Value}' ";
                        break;
                    default:
                        strSet += $" {item.Key}={item.Value} ";
                        break;
                }
            }
            return $"update {table} set {strSet} where 1=1 {condition}";
        }
 
 
 
 
        /// <summary>
        /// 将List转换成DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dt = new DataTable();
            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dt.Columns.Add(property.Name, property.PropertyType);
            }
            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }
                dt.Rows.Add(values);
            }
            return dt;
        }
 
 
        /// <summary>
        /// 将List转换为DataTable
        /// </summary>
        /// <param name="list">请求数据</param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> list)
        {
            //创建一个名为"tableName"的空表
            DataTable dt = new DataTable("tableName");
 
            //创建传入对象名称的列
            foreach (var item in list.FirstOrDefault().GetType().GetProperties())
            {
                dt.Columns.Add(item.Name);
            }
            //循环存储
            foreach (var item in list)
            {
                //新加行
                DataRow value = dt.NewRow();
                //根据DataTable中的值,进行对应的赋值
                foreach (DataColumn dtColumn in dt.Columns)
                {
                    int i = dt.Columns.IndexOf(dtColumn);
                    //基元元素,直接复制,对象类型等,进行序列化
                    if (value.GetType().IsPrimitive)
                    {
                        value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
                    }
                    else
                    {
                        value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item));
                    }
                }
                dt.Rows.Add(value);
            }
            return dt;
        }
 
    }
 
}