用Linq查询中的值填充DataTable

问题描述:

我有一个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 
        }; 

我希望从这个查询中加载信息到我的数据表。

如果有一个选项没有扩展任何方法,我会很高兴听到他们,但任何帮助将不胜感激。

问候, 大卫

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); 

从.net 3.5起,CopyToDataTable方法可能是你追求的。