C# DataTable에서 솔리드 클래스 객체 인스턴스로 변환

1314 단어
 
  
public class User
{
        public int ID { get; set; }
        public string Name { get; set; }
}

// :
//User
// :ID、Name    

그러면 DataTable를 실체 대상으로 바꾸는 방법을 작성해서 DataTable를 편리하게 해야 할지도 모른다.Rows를 획득하여 채웁니다.
다음은 제가 쓴 일반적인 방법입니다. 공유+기록을 나중에 직접 Copy를 할 수 있도록~
 
  
private static List TableToEntity(DataTable dt) where T : class,new()
{
    Type type = typeof(T);
    List list = new List();

    foreach (DataRow row in dt.Rows)
    {
        PropertyInfo[] pArray = type.GetProperties();
        T entity = new T();
        foreach (PropertyInfo p in pArray)
        {
            if (row[p.Name] is Int64)
            {
                p.SetValue(entity, Convert.ToInt32(row[p.Name]), null);
                continue;
            }
            p.SetValue(entity, row[p.Name], null);
        }
        list.Add(entity);
    }
    return list;
}
  

// :

List userList = TableToEntity(YourDataTable);

좋은 웹페이지 즐겨찾기