写这个东西主要是当时 需要同时用到2个系统的数据,合并在一起操作,有点像SQL中的 left join 东西写得有点繁琐 ,当时准备用.net自己的 Merge()方面但是好像不行不符合我的要求 无奈之下写下这些
/// <summary>
/// 2个DataTable合并DataTable
/// </summary>
/// <param name="FT"> DataTable</param>
/// <param name="LT">DataTable</param>
/// <param name="FtKeyName">关联的字段</param>
/// <param name="LtKeyName">关联字段</param>
/// <param name="AllColumnsName">要合并的字段</param>
/// <returns></returns>
public static DataTable MergeTable(DataTable FT, DataTable LT, string FtKeyName, string LtKeyName, params string[] AllColumnsName)
{
for (int i = 0; i < AllColumnsName.Length; i++)
{
FT.Columns.Add(AllColumnsName[i]);
}
foreach (DataRow row in FT.Rows)
{
for (int i = 0; i < LT.Rows.Count; i++)
{
if (row[FtKeyName].ToString().Trim() == LT.Rows[i][LtKeyName].ToString().Trim())
{
for (int j = 0; j < AllColumnsName.Length; j++)
{
row[AllColumnsName[j]] = LT.Rows[i][AllColumnsName[j]];
}
}
}
}
return FT;
}
/// <summary>
/// 将实体转换成具有相同结构的DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model">要转换的实体</param>
/// <returns></returns>
public static DataTable ToDataTable<T>(List<T> model)
{
//检查实体集合不能为空
if (model == null)
{
throw new Exception("需转换的集合为空");
}
//取出第一个实体的所有Propertie
Type entityType = model.GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
DataTable dt = new DataTable();
for (int i = 0; i < entityProperties.Length; i++)
{
dt.Columns.Add(entityProperties[i].Name, entityProperties[i].GetType());
}
foreach (object entity in model)
{
//检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entity);
}
return dt;
}
/// <summary>
/// 对象数组转换成DataTable
/// </summary>
/// <param name="entities"></param>
/// <returns></returns>
public static DataTable FillToDataTable(object[] entities)
{
Type type = entities.GetType().GetElementType();
PropertyInfo[] infoList = type.GetProperties();
DataTable table = new DataTable();
for (int i = 0; i < infoList.Length; i++)
{
PropertyInfo info = infoList[i];
if (IsBaseType(info.GetType()))
{
continue;
}
DataColumn column = new DataColumn();
column.ColumnName = info.Name;
column.DataType = info.PropertyType;
table.Columns.Add(column);
}
for (int i = 0; i < entities.Length; i++)
{
object obj = entities[i];
DataRow newRow = table.NewRow();
for (int j = 0; j < infoList.Length; j++)
{
PropertyInfo info = infoList[j];
if (IsBaseType(info.GetType()))
{
continue;
}
string name = info.Name;
object value = info.GetValue(obj, null);
if (value != null)
{
newRow[name] = value;
}
}
table.Rows.Add(newRow);
}
return table;
}
/// <summary>
/// 验证是否同一类型
/// </summary>
/// <param name="type">Type</param>
/// <returns>根据返回验证结果</returns>
private static bool IsBaseType(Type type)
{
return (type.IsValueType || type.IsPrimitive || type == typeof(string));
}