我有一个方法,它本质上把一个数据表转换成一个我称之为“包”的对象列表。每个会话多次调用此代码,许多会话同时运行,有时有数千行。因此,我需要尽可能快地完成任务。我有一个XML文件,其中包含数据列到属性的映射。优化的主要方法是
ConvertRowToBag
-传入的类型参数是派生自
BagBase
.
这是一段很长的代码,但是任何提示都会非常感谢。
public class BagBase
{
private static Dictionary<string, PropertyInfo> propertyDictionary = new Dictionary<string, PropertyInfo>();
private static DataTable mappings = new DataTable("Mappings");
private static bool MappingExists(string columnName, Type type)
{
DataRow [] rows = BagBase.mappings.Select(String.Format("Type = '{0}' and ColumnName = '{1}'", type.Name, columnName));
return (rows != null && rows.Length > 0);
}
protected static List<BagBase> ConvertTableToBags(DataTable table, Type outputType)
{
Trace.TraceInformation(String.Format("ConvertTableToBags : table={0} Type={1}", table.TableName, outputType.Name));
List<BagBase> result = new List<BagBase>();
foreach (DataRow row in table.Rows)
{
result.Add(ConvertRowToBag(outputType, row));
}
Trace.TraceInformation("ConvertTableToBags Finished.");
return result;
}
protected static BagBase ConvertRowToBag(Type outputType, DataRow row)
{
BagBase bag = Activator.CreateInstance(outputType) as BagBase;
foreach (DataColumn column in row.Table.Columns)
{
if (BagBase.MappingExists(column.ColumnName, outputType))
{
PropertyInfo property;
string columnProperty = String.Format("{0}={1}", column.ColumnName, outputType.Name);
if (!propertyDictionary.ContainsKey(columnProperty))
{
property = outputType.GetProperty(BagBase.GetColumnMapping(column.ColumnName, outputType));
propertyDictionary.Add(columnProperty, property);
}
else
{
property = propertyDictionary[columnProperty];
}
if (property != null)
{
if (!row.IsNull(column))
{
if (property.PropertyType.BaseType != null && property.PropertyType.BaseType == typeof(Enum))
{
if (column.DataType != typeof(String))
{
property.SetValue(bag, Enum.ToObject(property.PropertyType, row[column]), null);
}
else
{
property.SetValue(bag, Enum.ToObject(property.PropertyType, Convert.ToChar(row[column])), null);
}
}
else if (property.PropertyType == typeof(DateTime?))
{
property.SetValue(bag, (DateTime?)row[column], null);
}
else
{
property.SetValue(bag, Convert.ChangeType(row[column], property.PropertyType), null);
}
}
else
{
if (column.DataType == typeof(String))
{
property.SetValue(bag, String.Empty, null);
}
}
string propertyKey = String.Format("{0}.{1}", outputType.Name, property.Name);
if (!columnCaptions.ContainsKey(propertyKey))
{
columnCaptions.Add(propertyKey, column.Caption);
}
}
}
else
{
if (bag.OtherInformation == null)
{
bag.OtherInformation = new Dictionary<string, string>();
}
bag.OtherInformation.Add(column.ColumnName, !row.IsNull(column) ? row[column].ToString() : String.Empty);
}
}
return bag;
}
}