2014-07-22 2 views
1

아래의 로직은 데이터 세트에 단일 datatable을 가지고 있으면 잘 작동하지만, 데이터 세트에 두 개의 테이블이있는 경우 아래 로직을 어떻게 수정할 수 있습니까?어떻게 여러 테이블을 가진 datset을 generic리스트로 변환합니까

var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Employee{Name =  dataRow.Field<string>("Name")}.ToList(); 

Public class Employee 
{ 
public string name; 
public string ID; 
public Jobdetails job; 
} 

Public class Jobdetails 
{ 
public string role; 
public string salary; 
} 

것은 내가 거기에 데이터 세트에서 두 개의 테이블 또는 두 개의 테이블이있는 not.if 내가이 있는지 여부를 확인해야 .. 내가 Employee 클래스와 그 안에 하나의 중첩 된 객체가 있다고 가정 할 수 있습니다 직원 클래스의 첫 번째 테이블 (직원 이름과 ID)을 Employee 클래스에로드하고 두 번째 테이블 (역할 및 급여 열 포함)을 Employee 클래스에로드합니다.

테이블이 하나만있는 경우 직원 테이블에 첫 번째 테이블을로드하고 두 번째 테이블이 없으므로 jobdetails 개체를 null로 유지해야합니다.

위의 시나리오를 달성하는 가장 좋은 방법은 무엇입니까?

+0

데이터 세트의 테이블 수를 다음과 같이 확인할 수 있습니다. ds.Table.Count & 테이블 번호가 2 인 경우 테이블 [0]에서 테이블 [1]로 바꿀 수있는 두 번째 테이블에 대해 직원과 동일한 목록으로 변환 할 수 있습니다. – GMD

답변

0
public static DataTable ConvertToDatatable<T>(this IList<T> data) 
     { 
      PropertyDescriptorCollection props = 
       TypeDescriptor.GetProperties(typeof(T)); 
      DataTable table = new DataTable(); 
      for (int i = 0; i < props.Count; i++) 
      { 
       PropertyDescriptor prop = props[i]; 
       table.Columns.Add(prop.Name, prop.PropertyType); 
      } 
      object[] values = new object[props.Count]; 
      foreach (T item in data) 
      { 
       for (int i = 0; i < values.Length; i++) 
       { 
        values[i] = props[i].GetValue(item); 
       } 
       table.Rows.Add(values); 
      } 
      return table; 
     } 






DataTable dtList = ConvertToDatatable(request.Members);