2012-03-12 24 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 
        }; 

このクエリの情報をデータテーブルにロードします。

方法を拡張せずに行うオプションがある場合、私はそれらを聞いて非常にうれしいでしょうが、どんな助けもありがとうと思います。以降.NET 3.5から

よろしく、 デビッド

答えて

0

私はそれを見つけたと信じてOK:それを使用するために今すぐ

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

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

は、拡張メソッドを追加すること

DataTable dt = LINQToDataTable(data); 
関連する問題