我有这个扩展方法,它将DataTable转换为List,
public static List<T> ToList<T>(this DataTable table) where T : new()
{
var map = new List<Tuple<DataColumn, PropertyInfo>>();
foreach (var pi in typeof(T).GetProperties())
{
if (table.Columns.Contains(pi.Name))
{
map.Add(new Tuple<DataColumn, PropertyInfo>(table.Columns[pi.Name], pi));
}
}
var list = new List<T>(table.Rows.Count);
foreach (DataRow row in table.Rows)
{
var item = new T();
foreach (var pair in map)
{
object value = row[pair.Item1];
if (value is DBNull)
{
value = null;
}
var prop = pair.Item2;
prop.SetValue(item, Convert.ChangeType(value, prop.PropertyType), null);
}
list.Add(item);
}
return list;
}
但是大部分时间我都有复杂的对象类,比如
public enum ServiceCenterType
{
MOLOffice = 1,
Tasheel = 2
}
public class ServiceCenter : BusinessObjectEntity
{
public ServiceCenter()
{
Location = new Location();
Contact = new Contact();
}
public Contact Contact { get; set; }
public Location Location { get; set; }
public ServiceCenterType Type { get; set; }
}
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public class Contact
{
public string Address { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public string Fax { get; set; }
public string Email { get; set; }
public string Website { get; set; }
public string Twitter { get; set; }
public string Facebook { get; set; }
public Emirates Emirate { get; set; }
}
在我的DataTable中,我有像Contact.Address,Location.Latitude等列?如何修改上述扩展方法以支持我的场景?
答案 0 :(得分:0)
您也应该从类中获取字段,然后再次跟踪它们的属性
FieldInfo[] fields = typeof(T).GetFields(); // Obtain all fields
foreach (var field in fields) // Loop through fields
{
foreach (var pi in typeof(T).GetProperties())
{
}
}