我有这样的代码:
public static void ImportData()
{
string[] entites = new string[]
{
"Entity1",
"Entity2",
"Entity3"
};
using (var db = new DatabaseContext())
{
foreach (var entity in entites)
{
// the next two lines don't compile,
// i'm just including them to show my intentions
List<string> cols = typeof(entity).GetProperties().Select(a => a.Name).ToList();
List<entity> rows = db.entity.ToList();
foreach (var row in rows)
{
foreach (var col in cols)
{
// do stuff
var propertyInfo = row.GetType().GetProperty(col);
var propertyType = propertyInfo.PropertyType;
if (propertyType == typeof(double?))
{
var val = (double?)row.GetType().GetProperty(col).GetValue(row);
// do stuff
}
else if (propertyType == typeof(decimal?))
{
var val = (decimal?)row.GetType().GetProperty(col).GetValue(row);
// do stuff
}
}
}
}
}
}
我遇到的问题是entities
- 即。如果我实际使用“Entity1”等而不是循环遍历我的所有实体,则上面的代码有效。如何让cols
androws
集合成为可以迭代的通用集合?