You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
3.4 KiB
C#
89 lines
3.4 KiB
C#
using Mesnac.Action.ChemicalWeighing;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Mesnac.Action.ChemicalWeighing
|
|
{
|
|
public static class DataTableHelper
|
|
{
|
|
#region DataTable 转换成泛型List
|
|
/// <summary>
|
|
/// DataTable 转换成泛型List
|
|
/// </summary>
|
|
/// <typeparam name="T">实体对象类</typeparam>
|
|
/// <param name="dt">数据DatatTable</param>
|
|
/// <param name="objList">List集合</param>
|
|
/// <param name="isNullEmpty">空字符是否需要</param>
|
|
/// <returns>List<实体对象></returns>
|
|
public static List<Hw_WareHouseSubView> DataTableToList(this DataTable dt, List<Hw_WareHouseSubView> objList = null, bool isNullEmpty = true)
|
|
{
|
|
if (dt == null)
|
|
{
|
|
objList = null;
|
|
}
|
|
if (objList == null)
|
|
{
|
|
objList = new List<Hw_WareHouseSubView>();
|
|
}
|
|
var columnNames = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName).ToList();
|
|
var properties = typeof(Hw_WareHouseSubView).GetProperties();
|
|
object value = null;
|
|
foreach (DataRow row in dt.Rows)
|
|
{
|
|
var t = Activator.CreateInstance<Hw_WareHouseSubView>();
|
|
{
|
|
foreach (PropertyInfo pro in properties)
|
|
{
|
|
if (!pro.CanWrite)
|
|
{
|
|
continue;
|
|
}
|
|
if (dt.Columns.Contains(pro.Name.ToUpper()))
|
|
{
|
|
value = row[pro.Name];
|
|
if (value is System.DBNull)
|
|
{
|
|
value = null;
|
|
if (pro.PropertyType.FullName == "System.String")
|
|
{
|
|
value = string.Empty;
|
|
}
|
|
}
|
|
if (isNullEmpty)
|
|
{
|
|
if (pro.PropertyType.FullName == "System.String" && string.IsNullOrEmpty(value.ToString().Trim()))
|
|
{
|
|
value = string.Empty;
|
|
}
|
|
}
|
|
if (pro.PropertyType.IsGenericType
|
|
&& pro.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
|
|
&& value != null)
|
|
{
|
|
pro.SetValue(t, Convert.ChangeType(value, Nullable.GetUnderlyingType(pro.PropertyType)), null);
|
|
}
|
|
else if (pro.PropertyType.IsEnum)
|
|
{
|
|
pro.SetValue(t, Convert.ChangeType(value, Enum.GetUnderlyingType(pro.PropertyType)), null);
|
|
}
|
|
else
|
|
{
|
|
pro.SetValue(t, value, null);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
objList.Add(t);
|
|
}
|
|
return objList;
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|