2012-03-12 94 views
0

我有一個linq查詢運行良好。用Linq查詢中的值填充DataTable

var data = from c in context.C 
        where c.ID == 1 
        select new 
        { 
         cc = c.CC, 
         oc= c.OC, 
         ec = c.EC 
        }; 

我希望從這個查詢中加載信息到我的數據表。

如果有一個選項沒有擴展任何方法,我會很高興聽到他們,但任何幫助將不勝感激。

問候, 大衛

回答

0

OK,我相信我發現:

var data = from c in context.C 
       where c.ID == 1 
       select new 
       { 
        cc = c.CC, 
        oc= c.OC, 
        ec = c.EC 
       }; 

添加一個擴展方法:

use System.Reflection; 
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) 
     { 


      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 dt = LINQToDataTable(data);