2013-08-21 2 views
0

내 코드에서 쿼리 목록을 테이블로 변환해야하는 경우가 발생합니다. 그것이 어떻게이 보일 것 - 다양한 .cs 파일의 방법을 복제하는 대신Reachable 클래스를 DataTable LINQToDataTable에서 제거하십시오. <T>()?

DataTable gridTable = LINQToDataTable(GetGrids); // Loads Query into Table 

:

//Attach query results to DataTables 
    public DataTable LINQToDataTable<T>(IEnumerable<T> varlist) 
    { 
     DataTable dtReturn = new DataTable(); 

     // column names 
     PropertyInfo[] oProps = null; 

     if (varlist == null) return dtReturn; 

     foreach (T rec in varlist) 
     { 
      // Use reflection to get property names, to create table, Only first time, others will follow 
      if (oProps == null) 
      { 
       oProps = ((Type)rec.GetType()).GetProperties(); 
       foreach (PropertyInfo pi in oProps) 
       { 
        Type colType = pi.PropertyType; 

        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() 
        == typeof(Nullable<>))) 
        { 
         colType = colType.GetGenericArguments()[0]; 
        } 

        dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); 
       } 
      } 

      DataRow dr = dtReturn.NewRow(); 

      foreach (PropertyInfo pi in oProps) 
      { 
       dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue 
       (rec, null); 
      } 

      dtReturn.Rows.Add(dr); 
     } 
     return dtReturn; 
    } 

는 다음 예에서 완벽하게 작동 : 나는 이것을 달성하기 위해 다음과 같은 방법을 사용 나에게 다음과 같이 쓸 수 것이 자신의 유틸리티 클래스 :

DataTable gridTable = Utility.LINQToDataTable(GetGrids); // Loads Query into Table 

수많은 중복을 피하기 위해도록을 ??

답변

1
Utility 전화로 방법을 이동하고 당신이 그것을 호출 할 수 있습니다 그것은 지금

public class Utility 
{ 
    public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist) 
    { 
     // code .... 
    } 

} 

static로 만들

다음과 같이

DataTable gridTable = Utility.LINQToDataTable(GetGrids); 
1
public static class EnumerableExtensions 
{ 
    public static DataTable ToDataTable<T>(this IEnumerable<T> varlist) 
    { 
     // .. existing code here .. 
    } 
} 

를 사용

GetGrids.ToDataTable(); 
// just like the others 
GetGrids.ToList(); 
+0

고마워 티모, 너도 옳았다 :) 다 mith가 투표를했습니다. 순전히 그가 부탁 한대로 정확하게 전화를했기 때문에 기존의 코드를 완전히 제자리에 남겨 두었습니다. –